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/modules/consul.py
agent_members
python
def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret
Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L471-L504
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_self
python
def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret
Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L507-L537
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_maintenance
python
def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret
Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L540-L594
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_leave
python
def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret
Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L644-L684
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_check_register
python
def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret
The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L687-L772
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_check_deregister
python
def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret
The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L775-L813
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_check_warn
python
def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret
This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L865-L911
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_service_register
python
def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret
The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L963-L1074
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_service_deregister
python
def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret
Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1077-L1117
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
agent_service_maintenance
python
def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret
Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1120-L1175
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
session_create
python
def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret
Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1178-L1266
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
session_list
python
def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret
Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1269-L1313
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
session_destroy
python
def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret
Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1316-L1361
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
session_info
python
def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret
Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1364-L1403
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
catalog_register
python
def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret
Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1406-L1564
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
catalog_datacenters
python
def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret
Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1629-L1656
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
catalog_nodes
python
def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret
Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1659-L1693
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
health_node
python
def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret
Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1818-L1856
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
health_checks
python
def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret
Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1859-L1897
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
health_state
python
def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret
Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1952-L2000
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
acl_delete
python
def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret
Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2189-L2234
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
acl_info
python
def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret
Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2237-L2272
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
acl_list
python
def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret
List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2323-L2358
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
event_fire
python
def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret
List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2361-L2421
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
saltstack/salt
salt/modules/consul.py
event_list
python
def event_list(consul_url=None, token=None, **kwargs): ''' List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: query_params = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') function = 'event/list/' ret = _query(consul_url=consul_url, token=token, query_params=query_params, function=function) return ret
List the recent events. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2424-L2459
[ "def _query(function,\n consul_url,\n token=None,\n method='GET',\n api_version='v1',\n data=None,\n query_params=None):\n '''\n Consul object method function to construct and execute on the API URL.\n\n :param api_url: The Consul api url.\n :param api_version The Consul api version\n :param function: The Consul api function to perform.\n :param method: The HTTP method, e.g. GET or POST.\n :param data: The data to be sent for POST method. This param is ignored for GET requests.\n :return: The json response from the API call or False.\n '''\n\n if not query_params:\n query_params = {}\n\n ret = {'data': '',\n 'res': True}\n\n if not token:\n token = _get_token()\n\n headers = {\"X-Consul-Token\": token, \"Content-Type\": \"application/json\"}\n base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version))\n url = urllib.parse.urljoin(base_url, function, False)\n\n if method == 'GET':\n data = None\n else:\n if data is None:\n data = {}\n data = salt.utils.json.dumps(data)\n\n result = salt.utils.http.query(\n url,\n method=method,\n params=query_params,\n data=data,\n decode=True,\n status=True,\n header_dict=headers,\n opts=__opts__,\n )\n\n if result.get('status', None) == http_client.OK:\n ret['data'] = result.get('dict', result)\n ret['res'] = True\n elif result.get('status', None) == http_client.NO_CONTENT:\n ret['res'] = False\n elif result.get('status', None) == http_client.NOT_FOUND:\n ret['data'] = 'Key not found.'\n ret['res'] = False\n else:\n if result:\n ret['data'] = result\n ret['res'] = True\n else:\n ret['res'] = False\n return ret\n", "def _get_config():\n '''\n Retrieve Consul configuration\n '''\n return __salt__['config.get']('consul.url') or \\\n __salt__['config.get']('consul:url')\n" ]
# -*- coding: utf-8 -*- ''' Interact with Consul https://www.consul.io ''' # Import Python Libs from __future__ import absolute_import, print_function, unicode_literals import base64 import logging # Import salt libs import salt.utils.http import salt.utils.json # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import http_client, urllib log = logging.getLogger(__name__) from salt.exceptions import SaltInvocationError # Don't shadow built-ins. __func_alias__ = { 'list_': 'list' } __virtualname__ = 'consul' def _get_config(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.url') or \ __salt__['config.get']('consul:url') def _get_token(): ''' Retrieve Consul configuration ''' return __salt__['config.get']('consul.token') or \ __salt__['config.get']('consul:token') def _query(function, consul_url, token=None, method='GET', api_version='v1', data=None, query_params=None): ''' Consul object method function to construct and execute on the API URL. :param api_url: The Consul api url. :param api_version The Consul api version :param function: The Consul api function to perform. :param method: The HTTP method, e.g. GET or POST. :param data: The data to be sent for POST method. This param is ignored for GET requests. :return: The json response from the API call or False. ''' if not query_params: query_params = {} ret = {'data': '', 'res': True} if not token: token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} base_url = urllib.parse.urljoin(consul_url, '{0}/'.format(api_version)) url = urllib.parse.urljoin(base_url, function, False) if method == 'GET': data = None else: if data is None: data = {} data = salt.utils.json.dumps(data) result = salt.utils.http.query( url, method=method, params=query_params, data=data, decode=True, status=True, header_dict=headers, opts=__opts__, ) if result.get('status', None) == http_client.OK: ret['data'] = result.get('dict', result) ret['res'] = True elif result.get('status', None) == http_client.NO_CONTENT: ret['res'] = False elif result.get('status', None) == http_client.NOT_FOUND: ret['data'] = 'Key not found.' ret['res'] = False else: if result: ret['data'] = result ret['res'] = True else: ret['res'] = False return ret def list_(consul_url=None, token=None, key=None, **kwargs): ''' List keys in Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :return: The list of keys. CLI Example: .. code-block:: bash salt '*' consul.list salt '*' consul.list key='web' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'recurse' in kwargs: query_params['recurse'] = 'True' # No key so recurse and show all values if not key: query_params['recurse'] = 'True' function = 'kv/' else: function = 'kv/{0}'.format(key) query_params['keys'] = 'True' query_params['separator'] = '/' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw=False): ''' Get key from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Return values recursively beginning at the value of key. :param decode: By default values are stored as Base64 encoded values, decode will return the whole key with the value decoded. :param raw: Simply return the decoded value of the key. :return: The keys in Consul. CLI Example: .. code-block:: bash salt '*' consul.get key='web/key1' salt '*' consul.get key='web' recurse=True salt '*' consul.get key='web' recurse=True decode=True By default values stored in Consul are base64 encoded, passing the decode option will show them as the decoded values. .. code-block:: bash salt '*' consul.get key='web' recurse=True decode=True raw=True By default Consult will return other information about the key, the raw option will return only the raw value. ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} function = 'kv/{0}'.format(key) if recurse: query_params['recurse'] = 'True' if raw: query_params['raw'] = True ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if ret['res']: if decode: for item in ret['data']: if item['Value'] is None: item['Value'] = "" else: item['Value'] = base64.b64decode(item['Value']) return ret def put(consul_url=None, token=None, key=None, value=None, **kwargs): ''' Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsigned value between 0 and 2^64-1. Clients can choose to use this however makes sense for their application. :param cas: This flag is used to turn the PUT into a Check-And-Set operation. :param acquire: This flag is used to turn the PUT into a lock acquisition operation. :param release: This flag is used to turn the PUT into a lock release operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.put key='web/key1' value="Hello there" salt '*' consul.put key='web/key1' value="Hello there" acquire='d5d371f4-c380-5280-12fd-8810be175592' salt '*' consul.put key='web/key1' value="Hello there" release='d5d371f4-c380-5280-12fd-8810be175592' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') # Invalid to specified these together conflicting_args = ['cas', 'release', 'acquire'] for _l1 in conflicting_args: for _l2 in conflicting_args: if _l1 in kwargs and _l2 in kwargs and _l1 != _l2: raise SaltInvocationError('Using arguments `{0}` and `{1}`' ' together is invalid.'.format(_l1, _l2)) query_params = {} available_sessions = session_list(consul_url=consul_url, return_list=True) _current = get(consul_url=consul_url, key=key) if 'flags' in kwargs: if kwargs['flags'] >= 0 and kwargs['flags'] <= 2**64: query_params['flags'] = kwargs['flags'] if 'cas' in kwargs: if _current['res']: if kwargs['cas'] == 0: ret['message'] = ('Key {0} exists, index ' 'must be non-zero.'.format(key)) ret['res'] = False return ret if kwargs['cas'] != _current['data']['ModifyIndex']: ret['message'] = ('Key {0} exists, but indexes ' 'do not match.'.format(key)) ret['res'] = False return ret query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Key {0} does not exists, ' 'CAS argument can not be used.'.format(key)) ret['res'] = False return ret if 'acquire' in kwargs: if kwargs['acquire'] not in available_sessions: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False return ret query_params['acquire'] = kwargs['acquire'] if 'release' in kwargs: if _current['res']: if 'Session' in _current['data']: if _current['data']['Session'] == kwargs['release']: query_params['release'] = kwargs['release'] else: ret['message'] = '{0} locked by another session.'.format(key) ret['res'] = False return ret else: ret['message'] = '{0} is not a valid session.'.format(kwargs['acquire']) ret['res'] = False else: log.error('Key {0} does not exist. Skipping release.') data = value function = 'kv/{0}'.format(key) method = 'PUT' ret = _query(consul_url=consul_url, token=token, function=function, method=method, data=data, query_params=query_params) if ret['res']: ret['res'] = True ret['data'] = 'Added key {0} with value {1}.'.format(key, value) else: ret['res'] = False ret['data'] = 'Unable to add key {0} with value {1}.'.format(key, value) return ret def delete(consul_url=None, token=None, key=None, **kwargs): ''' Delete values from Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param recurse: Delete values recursively beginning at the value of key. :param cas: This flag is used to turn the DELETE into a Check-And-Set operation. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.delete key='web' salt '*' consul.delete key='web' recurse='True' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not key: raise SaltInvocationError('Required argument "key" is missing.') query_params = {} if 'recurse' in kwargs: query_params['recurse'] = True if 'cas' in kwargs: if kwargs['cas'] > 0: query_params['cas'] = kwargs['cas'] else: ret['message'] = ('Check and Set Operation ', 'value must be greater than 0.') ret['res'] = False return ret function = 'kv/{0}'.format(key) ret = _query(consul_url=consul_url, token=token, function=function, method='DELETE', query_params=query_params) if ret['res']: ret['res'] = True ret['message'] = 'Deleted key {0}.'.format(key) else: ret['res'] = False ret['message'] = 'Unable to delete key {0}.'.format(key) return ret def agent_checks(consul_url=None, token=None): ''' Returns the checks the local agent is managing :param consul_url: The Consul server URL. :return: Returns the checks the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_checks ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/checks' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_services(consul_url=None, token=None): ''' Returns the services the local agent is managing :param consul_url: The Consul server URL. :return: Returns the services the local agent is managing CLI Example: .. code-block:: bash salt '*' consul.agent_services ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/services' ret = _query(consul_url=consul_url, function=function, token=token, method='GET') return ret def agent_members(consul_url=None, token=None, **kwargs): ''' Returns the members as seen by the local serf agent :param consul_url: The Consul server URL. :return: Returns the members as seen by the local serf agent CLI Example: .. code-block:: bash salt '*' consul.agent_members ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/members' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_self(consul_url=None, token=None): ''' Returns the local node configuration :param consul_url: The Consul server URL. :return: Returns the local node configuration CLI Example: .. code-block:: bash salt '*' consul.agent_self ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'agent/self' ret = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) return ret def agent_maintenance(consul_url=None, token=None, **kwargs): ''' Manages node maintenance mode :param consul_url: The Consul server URL. :param enable: The enable flag is required. Acceptable values are either true (to enter maintenance mode) or false (to resume normal operation). :param reason: If provided, its value should be a text string explaining the reason for placing the node into maintenance mode. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_maintenance enable='False' reason='Upgrade in progress' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/maintenance' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Agent maintenance mode ' '{0}ed.'.format(kwargs['enable'])) else: ret['res'] = True ret['message'] = 'Unable to change maintenance mode for agent.' return ret def agent_join(consul_url=None, token=None, address=None, **kwargs): ''' Triggers the local agent to join a node :param consul_url: The Consul server URL. :param address: The address for the agent to connect to. :param wan: Causes the agent to attempt to join using the WAN pool. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_join address='192.168.1.1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not address: raise SaltInvocationError('Required argument "address" is missing.') if 'wan' in kwargs: query_params['wan'] = kwargs['wan'] function = 'agent/join/{0}'.format(address) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Agent joined the cluster' else: ret['res'] = False ret['message'] = 'Unable to join the cluster.' return ret def agent_leave(consul_url=None, token=None, node=None): ''' Used to instruct the agent to force a node into the left state. :param consul_url: The Consul server URL. :param node: The node the agent will force into left state :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_leave node='web1.example.com' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') function = 'agent/force-leave/{0}'.format(node) res = _query(consul_url=consul_url, function=function, token=token, method='GET', query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Node {0} put in leave state.'.format(node) else: ret['res'] = False ret['message'] = 'Unable to change state for {0}.'.format(node) return ret def agent_check_register(consul_url=None, token=None, **kwargs): ''' The register endpoint is used to add a new check to the local agent. :param consul_url: The Consul server URL. :param name: The description of what the check is for. :param id: The unique name to use for the check, if not provided 'name' is used. :param notes: Human readable description of the check. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_register name='Memory Utilization' script='/usr/local/bin/check_mem.py' interval='15s' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if True not in [True for item in ('script', 'http', 'ttl') if item in kwargs]: ret['message'] = 'Required parameter "script" or "http" is missing.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] if 'notes' in kwargs: data['Notes'] = kwargs['notes'] if 'script' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['Script'] = kwargs['script'] data['Interval'] = kwargs['interval'] if 'http' in kwargs: if 'interval' not in kwargs: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret data['HTTP'] = kwargs['http'] data['Interval'] = kwargs['interval'] if 'ttl' in kwargs: data['TTL'] = kwargs['ttl'] function = 'agent/check/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Check {0} added to agent.'.format(kwargs['name'])) else: ret['res'] = False ret['message'] = 'Unable to add check to agent.' return ret def agent_check_deregister(consul_url=None, token=None, checkid=None): ''' The agent will take care of deregistering the check from the Catalog. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_deregister checkid='Memory Utilization' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') function = 'agent/check/deregister/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, method='GET') if res['res']: ret['res'] = True ret['message'] = ('Check {0} removed from agent.'.format(checkid)) else: ret['res'] = False ret['message'] = 'Unable to remove check from agent.' return ret def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to passing and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to mark as passing. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_pass checkid='redis_check1' note='Forcing check into passing state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/pass/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as passing.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to warning and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_warn checkid='redis_check1' note='Forcing check into warning state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/warn/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as warning.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ''' This endpoint is used with a check that is of the TTL type. When this is called, the status of the check is set to critical and the TTL clock is reset. :param consul_url: The Consul server URL. :param checkid: The ID of the check to deregister from Consul. :param note: A human-readable message with the status of the check. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_check_fail checkid='redis_check1' note='Forcing check into critical state.' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') if 'note' in kwargs: query_params['note'] = kwargs['note'] function = 'agent/check/fail/{0}'.format(checkid) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params, method='GET') if res['res']: ret['res'] = True ret['message'] = 'Check {0} marked as critical.'.format(checkid) else: ret['res'] = False ret['message'] = 'Unable to update check {0}.'.format(checkid) return ret def agent_service_register(consul_url=None, token=None, **kwargs): ''' The used to add a new service, with an optional health check, to the local agent. :param consul_url: The Consul server URL. :param name: A name describing the service. :param address: The address used by the service, defaults to the address of the agent. :param port: The port used by the service. :param id: Unique ID to identify the service, if not provided the value of the name parameter is used. :param tags: Identifying tags for service, string or list. :param script: If script is provided, the check type is a script, and Consul will evaluate that script based on the interval parameter. :param http: Check will perform an HTTP GET request against the value of HTTP (expected to be a URL) based on the interval parameter. :param check_ttl: If a TTL type is used, then the TTL update endpoint must be used periodically to update the state of the check. :param check_interval: Interval at which the check should run. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_register name='redis' tags='["master", "v1"]' address="127.0.0.1" port="8080" check_script="/usr/local/bin/check_redis.py" interval="10s" ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret lc_kwargs = dict() for k, v in six.iteritems(kwargs): lc_kwargs[k.lower()] = v if 'name' in lc_kwargs: data['Name'] = lc_kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'address' in lc_kwargs: data['Address'] = lc_kwargs['address'] if 'port' in lc_kwargs: data['Port'] = lc_kwargs['port'] if 'id' in lc_kwargs: data['ID'] = lc_kwargs['id'] if 'tags' in lc_kwargs: _tags = lc_kwargs['tags'] if not isinstance(_tags, list): _tags = [_tags] data['Tags'] = _tags if 'enabletagoverride' in lc_kwargs: data['EnableTagOverride'] = lc_kwargs['enabletagoverride'] if 'check' in lc_kwargs: dd = dict() for k, v in six.iteritems(lc_kwargs['check']): dd[k.lower()] = v interval_required = False check_dd = dict() if 'script' in dd: interval_required = True check_dd['Script'] = dd['script'] if 'http' in dd: interval_required = True check_dd['HTTP'] = dd['http'] if 'ttl' in dd: check_dd['TTL'] = dd['ttl'] if 'interval' in dd: check_dd['Interval'] = dd['interval'] if interval_required: if 'Interval' not in check_dd: ret['message'] = 'Required parameter "interval" is missing.' ret['res'] = False return ret else: if 'Interval' in check_dd: del check_dd['Interval'] # not required, so ignore it if check_dd > 0: data['Check'] = check_dd # if empty, ignore it function = 'agent/service/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} registered on agent.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to register service {0}.'.format(kwargs['name']) return ret def agent_service_deregister(consul_url=None, token=None, serviceid=None): ''' Used to remove a service. :param consul_url: The Consul server URL. :param serviceid: A serviceid describing the service. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') function = 'agent/service/deregister/{0}'.format(serviceid) res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Service {0} removed from agent.'.format(serviceid) else: ret['res'] = False ret['message'] = 'Unable to remove service {0}.'.format(serviceid) return ret def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwargs): ''' Used to place a service into maintenance mode. :param consul_url: The Consul server URL. :param serviceid: A name of the service. :param enable: Whether the service should be enabled or disabled. :param reason: A human readable message of why the service was enabled or disabled. :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.agent_service_deregister serviceid='redis' enable='True' reason='Down for upgrade' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') if 'enable' in kwargs: query_params['enable'] = kwargs['enable'] else: ret['message'] = 'Required parameter "enable" is missing.' ret['res'] = False return ret if 'reason' in kwargs: query_params['reason'] = kwargs['reason'] function = 'agent/service/maintenance/{0}'.format(serviceid) res = _query(consul_url=consul_url, token=token, function=function, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = ('Service {0} set in ' 'maintenance mode.'.format(serviceid)) else: ret['res'] = False ret['message'] = ('Unable to set service ' '{0} to maintenance mode.'.format(serviceid)) return ret def session_create(consul_url=None, token=None, **kwargs): ''' Used to create a session. :param consul_url: The Consul server URL. :param lockdelay: Duration string using a "s" suffix for seconds. The default is 15s. :param node: Must refer to a node that is already registered, if specified. By default, the agent's own node name is used. :param name: A human-readable name for the session :param checks: A list of associated health checks. It is highly recommended that, if you override this list, you include the default "serfHealth". :param behavior: Can be set to either release or delete. This controls the behavior when a session is invalidated. By default, this is release, causing any locks that are held to be released. Changing this to delete causes any locks that are held to be deleted. delete is useful for creating ephemeral key/value entries. :param ttl: Session is invalidated if it is not renewed before the TTL expires :return: Boolean and message indicating success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_create node='node1' name='my-session' behavior='delete' ttl='3600s' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret data = {} if 'lockdelay' in kwargs: data['LockDelay'] = kwargs['lockdelay'] if 'node' in kwargs: data['Node'] = kwargs['node'] if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'checks' in kwargs: data['Touch'] = kwargs['touch'] if 'behavior' in kwargs: if not kwargs['behavior'] in ('delete', 'release'): ret['message'] = ('Behavior must be ', 'either delete or release.') ret['res'] = False return ret data['Behavior'] = kwargs['behavior'] if 'ttl' in kwargs: _ttl = kwargs['ttl'] if six.text_type(_ttl).endswith('s'): _ttl = _ttl[:-1] if int(_ttl) < 0 or int(_ttl) > 3600: ret['message'] = ('TTL must be ', 'between 0 and 3600.') ret['res'] = False return ret data['TTL'] = '{0}s'.format(_ttl) function = 'session/create' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Created session {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create session {0}.'.format(kwargs['name']) return ret def session_list(consul_url=None, token=None, return_list=False, **kwargs): ''' Used to list sessions. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param return_list: By default, all information about the sessions is returned, using the return_list parameter will return a list of session IDs. :return: A list of all available sessions. CLI Example: .. code-block:: bash salt '*' consul.session_list ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/list' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if return_list: _list = [] for item in ret['data']: _list.append(item['ID']) return _list return ret def session_destroy(consul_url=None, token=None, session=None, **kwargs): ''' Destroy session :param consul_url: The Consul server URL. :param session: The ID of the session to destroy. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_destroy session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/destroy/{0}'.format(session) res = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) if res['res']: ret['res'] = True ret['message'] = 'Created Service {0}.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = 'Unable to create service {0}.'.format(kwargs['name']) return ret def session_info(consul_url=None, token=None, session=None, **kwargs): ''' Information about a session :param consul_url: The Consul server URL. :param session: The ID of the session to return information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.session_info session='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not session: raise SaltInvocationError('Required argument "session" is missing.') query_params = {} if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'session/info/{0}'.format(session) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_register(consul_url=None, token=None, **kwargs): ''' Registers a new node, service, or check :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: The node to register. :param address: The address of the node. :param service: The service that will be registered. :param service_address: The address that the service listens on. :param service_port: The port for the service. :param service_id: A unique identifier for the service, if this is not provided "name" will be used. :param service_tags: Any tags associated with the service. :param check: The name of the health check to register :param check_status: The initial status of the check, must be one of unknown, passing, warning, or critical. :param check_service: The service that the check is performed against. :param check_id: Unique identifier for the service. :param check_notes: An opaque field that is meant to hold human-readable text. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' address='192.168.1.1' service='redis' service_address='127.0.0.1' service_port='8080' service_id='redis_server1' ''' ret = {} data = {} data['NodeMeta'] = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Required argument node argument is missing.' ret['res'] = False return ret if 'address' in kwargs: if isinstance(kwargs['address'], list): _address = kwargs['address'][0] else: _address = kwargs['address'] data['Address'] = _address else: ret['message'] = 'Required argument address argument is missing.' ret['res'] = False return ret if 'ip_interfaces' in kwargs: data['TaggedAddresses'] = {} for k in kwargs['ip_interfaces']: if kwargs['ip_interfaces'].get(k): data['TaggedAddresses'][k] = kwargs['ip_interfaces'][k][0] if 'service' in kwargs: data['Service'] = {} data['Service']['Service'] = kwargs['service'] if 'service_address' in kwargs: data['Service']['Address'] = kwargs['service_address'] if 'service_port' in kwargs: data['Service']['Port'] = kwargs['service_port'] if 'service_id' in kwargs: data['Service']['ID'] = kwargs['service_id'] if 'service_tags' in kwargs: _tags = kwargs['service_tags'] if not isinstance(_tags, list): _tags = [_tags] data['Service']['Tags'] = _tags if 'cpu' in kwargs: data['NodeMeta']['Cpu'] = kwargs['cpu'] if 'num_cpus' in kwargs: data['NodeMeta']['Cpu_num'] = kwargs['num_cpus'] if 'mem' in kwargs: data['NodeMeta']['Memory'] = kwargs['mem'] if 'oscode' in kwargs: data['NodeMeta']['Os'] = kwargs['oscode'] if 'osarch' in kwargs: data['NodeMeta']['Osarch'] = kwargs['osarch'] if 'kernel' in kwargs: data['NodeMeta']['Kernel'] = kwargs['kernel'] if 'kernelrelease' in kwargs: data['NodeMeta']['Kernelrelease'] = kwargs['kernelrelease'] if 'localhost' in kwargs: data['NodeMeta']['localhost'] = kwargs['localhost'] if 'nodename' in kwargs: data['NodeMeta']['nodename'] = kwargs['nodename'] if 'os_family' in kwargs: data['NodeMeta']['os_family'] = kwargs['os_family'] if 'lsb_distrib_description' in kwargs: data['NodeMeta']['lsb_distrib_description'] = kwargs['lsb_distrib_description'] if 'master' in kwargs: data['NodeMeta']['master'] = kwargs['master'] if 'check' in kwargs: data['Check'] = {} data['Check']['Name'] = kwargs['check'] if 'check_status' in kwargs: if kwargs['check_status'] not in ('unknown', 'passing', 'warning', 'critical'): ret['message'] = 'Check status must be unknown, passing, warning, or critical.' ret['res'] = False return ret data['Check']['Status'] = kwargs['check_status'] if 'check_service' in kwargs: data['Check']['ServiceID'] = kwargs['check_service'] if 'check_id' in kwargs: data['Check']['CheckID'] = kwargs['check_id'] if 'check_notes' in kwargs: data['Check']['Notes'] = kwargs['check_notes'] function = 'catalog/register' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = ('Catalog registration ' 'for {0} successful.'.format(kwargs['node'])) else: ret['res'] = False ret['message'] = ('Catalog registration ' 'for {0} failed.'.format(kwargs['node'])) ret['data'] = data return ret def catalog_deregister(consul_url=None, token=None, **kwargs): ''' Deregisters a node, service, or check :param consul_url: The Consul server URL. :param node: The node to deregister. :param datacenter: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param checkid: The ID of the health check to deregister. :param serviceid: The ID of the service to deregister. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.catalog_register node='node1' serviceid='redis_server1' checkid='redis_check1' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'datacenter' in kwargs: data['Datacenter'] = kwargs['datacenter'] if 'node' in kwargs: data['Node'] = kwargs['node'] else: ret['message'] = 'Node argument required.' ret['res'] = False return ret if 'checkid' in kwargs: data['CheckID'] = kwargs['checkid'] if 'serviceid' in kwargs: data['ServiceID'] = kwargs['serviceid'] function = 'catalog/deregister' res = _query(consul_url=consul_url, function=function, token=token, method='PUT', data=data) if res['res']: ret['res'] = True ret['message'] = 'Catalog item {0} removed.'.format(kwargs['node']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['node'])) return ret def catalog_datacenters(consul_url=None, token=None): ''' Return list of available datacenters from catalog. :param consul_url: The Consul server URL. :return: The list of available datacenters. CLI Example: .. code-block:: bash salt '*' consul.catalog_datacenters ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'catalog/datacenters' ret = _query(consul_url=consul_url, function=function, token=token) return ret def catalog_nodes(consul_url=None, token=None, **kwargs): ''' Return list of available nodes from catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available nodes. CLI Example: .. code-block:: bash salt '*' consul.catalog_nodes ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/nodes' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_services(consul_url=None, token=None, **kwargs): ''' Return list of available services rom catalog. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The list of available services. CLI Example: .. code-block:: bash salt '*' consul.catalog_services ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/services' ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_service(consul_url=None, token=None, service=None, **kwargs): ''' Information about the registered service. :param consul_url: The Consul server URL. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :return: Information about the requested service. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] function = 'catalog/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def catalog_node(consul_url=None, token=None, node=None, **kwargs): ''' Information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.catalog_service service='redis' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'catalog/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_node(consul_url=None, token=None, node=None, **kwargs): ''' Health information about the registered node. :param consul_url: The Consul server URL. :param node: The node to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_node node='node1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not node: raise SaltInvocationError('Required argument "node" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/node/{0}'.format(node) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_checks(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_checks service='redis1' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] function = 'health/checks/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_service(consul_url=None, token=None, service=None, **kwargs): ''' Health information about the registered service. :param consul_url: The Consul server URL. :param service: The service to request health information about. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param tag: Filter returned services with tag parameter. :param passing: Filter results to only nodes with all checks in the passing state. :return: Health information about the requested node. CLI Example: .. code-block:: bash salt '*' consul.health_service service='redis1' salt '*' consul.health_service service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not service: raise SaltInvocationError('Required argument "service" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if 'tag' in kwargs: query_params['tag'] = kwargs['tag'] if 'passing' in kwargs: query_params['passing'] = kwargs['passing'] function = 'health/service/{0}'.format(service) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def health_state(consul_url=None, token=None, state=None, **kwargs): ''' Returns the checks in the state provided on the path. :param consul_url: The Consul server URL. :param state: The state to show checks for. The supported states are any, unknown, passing, warning, or critical. The any state is a wildcard that can be used to return all checks. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :return: The checks in the provided state. CLI Example: .. code-block:: bash salt '*' consul.health_state state='redis1' salt '*' consul.health_state service='redis1' passing='True' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not state: raise SaltInvocationError('Required argument "state" is missing.') if 'dc' in kwargs: query_params['dc'] = kwargs['dc'] if state not in ('any', 'unknown', 'passing', 'warning', 'critical'): ret['message'] = 'State must be any, unknown, passing, warning, or critical.' ret['res'] = False return ret function = 'health/state/{0}'.format(state) ret = _query(consul_url=consul_url, function=function, token=token, query_params=query_params) return ret def status_leader(consul_url=None, token=None): ''' Returns the current Raft leader :param consul_url: The Consul server URL. :return: The address of the Raft leader. CLI Example: .. code-block:: bash salt '*' consul.status_leader ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/leader' ret = _query(consul_url=consul_url, function=function, token=token) return ret def status_peers(consul_url, token=None): ''' Returns the current Raft peer set :param consul_url: The Consul server URL. :return: Retrieves the Raft peers for the datacenter in which the agent is running. CLI Example: .. code-block:: bash salt '*' consul.status_peers ''' ret = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret function = 'status/peers' ret = _query(consul_url=consul_url, function=function, token=token) return ret def acl_create(consul_url=None, token=None, **kwargs): ''' Create a new ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_create ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/create' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Removing Catalog ' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_update(consul_url=None, token=None, **kwargs): ''' Update an ACL token. :param consul_url: The Consul server URL. :param name: Meaningful indicator of the ACL's purpose. :param id: Unique identifier for the ACL to update. :param type: Type is either client or management. A management token is comparable to a root user and has the ability to perform any action including creating, modifying, and deleting ACLs. :param rules: The Consul server URL. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_update ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' in kwargs: data['ID'] = kwargs['id'] else: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret if 'name' in kwargs: data['Name'] = kwargs['name'] else: raise SaltInvocationError('Required argument "name" is missing.') if 'type' in kwargs: data['Type'] = kwargs['type'] if 'rules' in kwargs: data['Rules'] = kwargs['rules'] function = 'acl/update' res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} created.'.format(kwargs['name']) else: ret['res'] = False ret['message'] = ('Adding ACL ' '{0} failed.'.format(kwargs['name'])) return ret def acl_delete(consul_url=None, token=None, **kwargs): ''' Delete an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean & message of success or failure. CLI Example: .. code-block:: bash salt '*' consul.acl_delete id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/delete/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} deleted.'.format(kwargs['id']) else: ret['res'] = False ret['message'] = ('Removing ACL ' '{0} failed.'.format(kwargs['id'])) return ret def acl_info(consul_url=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Information about the ACL requested. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/info/{0}'.format(kwargs['id']) ret = _query(consul_url=consul_url, data=data, method='GET', function=function) return ret def acl_clone(consul_url=None, token=None, **kwargs): ''' Information about an ACL token. :param consul_url: The Consul server URL. :param id: Unique identifier for the ACL to update. :return: Boolean, message of success or failure, and new ID of cloned ACL. CLI Example: .. code-block:: bash salt '*' consul.acl_info id='c1c4d223-91cb-3d1f-1ee8-f2af9e7b6716' ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/clone/{0}'.format(kwargs['id']) res = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'ACL {0} cloned.'.format(kwargs['name']) ret['ID'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if 'id' not in kwargs: ret['message'] = 'Required parameter "id" is missing.' ret['res'] = False return ret function = 'acl/list' ret = _query(consul_url=consul_url, token=token, data=data, method='PUT', function=function) return ret def event_fire(consul_url=None, token=None, name=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :param name: The name of the event to fire. :param dc: By default, the datacenter of the agent is queried; however, the dc can be provided using the "dc" parameter. :param node: Filter by node name. :param service: Filter by service name. :param tag: Filter by tag name. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.event_fire name='deploy' ''' ret = {} query_params = {} if not consul_url: consul_url = _get_config() if not consul_url: log.error('No Consul URL found.') ret['message'] = 'No Consul URL found.' ret['res'] = False return ret if not name: raise SaltInvocationError('Required argument "name" is missing.') if 'dc' in kwargs: query_params = kwargs['dc'] if 'node' in kwargs: query_params = kwargs['node'] if 'service' in kwargs: query_params = kwargs['service'] if 'tag' in kwargs: query_params = kwargs['tag'] function = 'event/fire/{0}'.format(name) res = _query(consul_url=consul_url, token=token, query_params=query_params, method='PUT', function=function) if res['res']: ret['res'] = True ret['message'] = 'Event {0} fired.'.format(name) ret['data'] = ret['data'] else: ret['res'] = False ret['message'] = ('Cloning ACL' 'item {0} failed.'.format(kwargs['name'])) return ret
saltstack/salt
salt/states/sysrc.py
managed
python
def managed(name, value, **kwargs): ''' Ensure a sysrc variable is set to a specific value. name The variable name to set value Value to set the variable to file (optional) The rc file to add the variable to. jail (option) the name or JID of the jail to set the value in. Example: .. code-block:: yaml syslogd: sysrc.managed: - name: syslogd_flags - value: -ss ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Check the current state current_state = __salt__['sysrc.get'](name=name, **kwargs) if current_state is not None: for rcname, rcdict in six.iteritems(current_state): if rcdict[name] == value: ret['result'] = True ret['comment'] = '{0} is already set to the desired value.'.format(name) return ret if __opts__['test'] is True: ret['comment'] = 'The value of "{0}" will be changed!'.format(name) ret['changes'] = { 'old': current_state, 'new': name+' = '+value+' will be set.' } # When test=true return none ret['result'] = None return ret new_state = __salt__['sysrc.set'](name=name, value=value, **kwargs) ret['comment'] = 'The value of "{0}" was changed!'.format(name) ret['changes'] = { 'old': current_state, 'new': new_state } ret['result'] = True return ret
Ensure a sysrc variable is set to a specific value. name The variable name to set value Value to set the variable to file (optional) The rc file to add the variable to. jail (option) the name or JID of the jail to set the value in. Example: .. code-block:: yaml syslogd: sysrc.managed: - name: syslogd_flags - value: -ss
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sysrc.py#L24-L81
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n" ]
# -*- coding: utf-8 -*- ''' State to work with sysrc ''' # Import Python libs from __future__ import absolute_import, unicode_literals, print_function # Import 3rd-party libs from salt.ext import six # define the module's virtual name __virtualname__ = 'sysrc' def __virtual__(): ''' Only load if sysrc executable exists ''' return __salt__['cmd.has_exec']('sysrc') def absent(name, **kwargs): ''' Ensure a sysrc variable is absent. name The variable name to set file (optional) The rc file to add the variable to. jail (option) the name or JID of the jail to set the value in. ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} # Check the current state current_state = __salt__['sysrc.get'](name=name, **kwargs) if current_state is None: ret['result'] = True ret['comment'] = '"{0}" is already absent.'.format(name) return ret if __opts__['test'] is True: ret['comment'] = '"{0}" will be removed!'.format(name) ret['changes'] = { 'old': current_state, 'new': '"{0}" will be removed.'.format(name) } # When test=true return none ret['result'] = None return ret new_state = __salt__['sysrc.remove'](name=name, **kwargs) ret['comment'] = '"{0}" was removed!'.format(name) ret['changes'] = { 'old': current_state, 'new': new_state } ret['result'] = True return ret
saltstack/salt
salt/client/ssh/wrapper/pillar.py
get
python
def get(key, default='', merge=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.14 Attempt to retrieve the named value from pillar, if the named value is not available return the passed default. The default return is an empty string. If the merge parameter is set to ``True``, the default will be recursively merged into the returned pillar data. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in pillar looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache merge Specify whether or not the retrieved values should be recursively merged into the passed default. .. versionadded:: 2015.5.0 delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' pillar.get pkg:apache ''' if merge: ret = salt.utils.data.traverse_dict_and_list(__pillar__, key, {}, delimiter) if isinstance(ret, collections.Mapping) and \ isinstance(default, collections.Mapping): return salt.utils.dictupdate.update(default, ret) return salt.utils.data.traverse_dict_and_list( __pillar__, key, default, delimiter)
.. versionadded:: 0.14 Attempt to retrieve the named value from pillar, if the named value is not available return the passed default. The default return is an empty string. If the merge parameter is set to ``True``, the default will be recursively merged into the returned pillar data. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in pillar looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache merge Specify whether or not the retrieved values should be recursively merged into the passed default. .. versionadded:: 2015.5.0 delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' pillar.get pkg:apache
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L17-L64
null
# -*- coding: utf-8 -*- ''' Extract the pillar data for this minion ''' from __future__ import absolute_import, print_function # Import python libs import collections # Import salt libs import salt.pillar import salt.utils.data import salt.utils.dictupdate from salt.defaults import DEFAULT_TARGET_DELIM def item(*args): ''' .. versionadded:: 0.16.2 Return one or more pillar entries CLI Examples: .. code-block:: bash salt '*' pillar.item foo salt '*' pillar.item foo bar baz ''' ret = {} for arg in args: try: ret[arg] = __pillar__[arg] except KeyError: pass return ret def raw(key=None): ''' Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles' ''' if key: ret = __pillar__.get(key, {}) else: ret = __pillar__ return ret def keys(key, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 2015.8.0 Attempt to retrieve a list of keys from the named value from the pillar. The value can also represent a value in a nested dict using a ":" delimiter for the dict, similar to how pillar.get works. delimiter Specify an alternate delimiter to use when traversing a nested dict CLI Example: .. code-block:: bash salt '*' pillar.keys web:sites ''' ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, KeyError, delimiter) if ret is KeyError: raise KeyError("Pillar key not found: {0}".format(key)) if not isinstance(ret, dict): raise ValueError("Pillar value in key {0} is not a dict".format(key)) return ret.keys() # Allow pillar.data to also be used to return pillar data items = raw data = items
saltstack/salt
salt/client/ssh/wrapper/pillar.py
item
python
def item(*args): ''' .. versionadded:: 0.16.2 Return one or more pillar entries CLI Examples: .. code-block:: bash salt '*' pillar.item foo salt '*' pillar.item foo bar baz ''' ret = {} for arg in args: try: ret[arg] = __pillar__[arg] except KeyError: pass return ret
.. versionadded:: 0.16.2 Return one or more pillar entries CLI Examples: .. code-block:: bash salt '*' pillar.item foo salt '*' pillar.item foo bar baz
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L67-L86
null
# -*- coding: utf-8 -*- ''' Extract the pillar data for this minion ''' from __future__ import absolute_import, print_function # Import python libs import collections # Import salt libs import salt.pillar import salt.utils.data import salt.utils.dictupdate from salt.defaults import DEFAULT_TARGET_DELIM def get(key, default='', merge=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.14 Attempt to retrieve the named value from pillar, if the named value is not available return the passed default. The default return is an empty string. If the merge parameter is set to ``True``, the default will be recursively merged into the returned pillar data. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in pillar looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache merge Specify whether or not the retrieved values should be recursively merged into the passed default. .. versionadded:: 2015.5.0 delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' pillar.get pkg:apache ''' if merge: ret = salt.utils.data.traverse_dict_and_list(__pillar__, key, {}, delimiter) if isinstance(ret, collections.Mapping) and \ isinstance(default, collections.Mapping): return salt.utils.dictupdate.update(default, ret) return salt.utils.data.traverse_dict_and_list( __pillar__, key, default, delimiter) def raw(key=None): ''' Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles' ''' if key: ret = __pillar__.get(key, {}) else: ret = __pillar__ return ret def keys(key, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 2015.8.0 Attempt to retrieve a list of keys from the named value from the pillar. The value can also represent a value in a nested dict using a ":" delimiter for the dict, similar to how pillar.get works. delimiter Specify an alternate delimiter to use when traversing a nested dict CLI Example: .. code-block:: bash salt '*' pillar.keys web:sites ''' ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, KeyError, delimiter) if ret is KeyError: raise KeyError("Pillar key not found: {0}".format(key)) if not isinstance(ret, dict): raise ValueError("Pillar value in key {0} is not a dict".format(key)) return ret.keys() # Allow pillar.data to also be used to return pillar data items = raw data = items
saltstack/salt
salt/client/ssh/wrapper/pillar.py
raw
python
def raw(key=None): ''' Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles' ''' if key: ret = __pillar__.get(key, {}) else: ret = __pillar__ return ret
Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L89-L110
null
# -*- coding: utf-8 -*- ''' Extract the pillar data for this minion ''' from __future__ import absolute_import, print_function # Import python libs import collections # Import salt libs import salt.pillar import salt.utils.data import salt.utils.dictupdate from salt.defaults import DEFAULT_TARGET_DELIM def get(key, default='', merge=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.14 Attempt to retrieve the named value from pillar, if the named value is not available return the passed default. The default return is an empty string. If the merge parameter is set to ``True``, the default will be recursively merged into the returned pillar data. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in pillar looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache merge Specify whether or not the retrieved values should be recursively merged into the passed default. .. versionadded:: 2015.5.0 delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' pillar.get pkg:apache ''' if merge: ret = salt.utils.data.traverse_dict_and_list(__pillar__, key, {}, delimiter) if isinstance(ret, collections.Mapping) and \ isinstance(default, collections.Mapping): return salt.utils.dictupdate.update(default, ret) return salt.utils.data.traverse_dict_and_list( __pillar__, key, default, delimiter) def item(*args): ''' .. versionadded:: 0.16.2 Return one or more pillar entries CLI Examples: .. code-block:: bash salt '*' pillar.item foo salt '*' pillar.item foo bar baz ''' ret = {} for arg in args: try: ret[arg] = __pillar__[arg] except KeyError: pass return ret def keys(key, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 2015.8.0 Attempt to retrieve a list of keys from the named value from the pillar. The value can also represent a value in a nested dict using a ":" delimiter for the dict, similar to how pillar.get works. delimiter Specify an alternate delimiter to use when traversing a nested dict CLI Example: .. code-block:: bash salt '*' pillar.keys web:sites ''' ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, KeyError, delimiter) if ret is KeyError: raise KeyError("Pillar key not found: {0}".format(key)) if not isinstance(ret, dict): raise ValueError("Pillar value in key {0} is not a dict".format(key)) return ret.keys() # Allow pillar.data to also be used to return pillar data items = raw data = items
saltstack/salt
salt/client/ssh/wrapper/pillar.py
keys
python
def keys(key, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 2015.8.0 Attempt to retrieve a list of keys from the named value from the pillar. The value can also represent a value in a nested dict using a ":" delimiter for the dict, similar to how pillar.get works. delimiter Specify an alternate delimiter to use when traversing a nested dict CLI Example: .. code-block:: bash salt '*' pillar.keys web:sites ''' ret = salt.utils.data.traverse_dict_and_list( __pillar__, key, KeyError, delimiter) if ret is KeyError: raise KeyError("Pillar key not found: {0}".format(key)) if not isinstance(ret, dict): raise ValueError("Pillar value in key {0} is not a dict".format(key)) return ret.keys()
.. versionadded:: 2015.8.0 Attempt to retrieve a list of keys from the named value from the pillar. The value can also represent a value in a nested dict using a ":" delimiter for the dict, similar to how pillar.get works. delimiter Specify an alternate delimiter to use when traversing a nested dict CLI Example: .. code-block:: bash salt '*' pillar.keys web:sites
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L113-L140
null
# -*- coding: utf-8 -*- ''' Extract the pillar data for this minion ''' from __future__ import absolute_import, print_function # Import python libs import collections # Import salt libs import salt.pillar import salt.utils.data import salt.utils.dictupdate from salt.defaults import DEFAULT_TARGET_DELIM def get(key, default='', merge=False, delimiter=DEFAULT_TARGET_DELIM): ''' .. versionadded:: 0.14 Attempt to retrieve the named value from pillar, if the named value is not available return the passed default. The default return is an empty string. If the merge parameter is set to ``True``, the default will be recursively merged into the returned pillar data. The value can also represent a value in a nested dict using a ":" delimiter for the dict. This means that if a dict in pillar looks like this:: {'pkg': {'apache': 'httpd'}} To retrieve the value associated with the apache key in the pkg dict this key can be passed:: pkg:apache merge Specify whether or not the retrieved values should be recursively merged into the passed default. .. versionadded:: 2015.5.0 delimiter Specify an alternate delimiter to use when traversing a nested dict .. versionadded:: 2015.5.0 CLI Example: .. code-block:: bash salt '*' pillar.get pkg:apache ''' if merge: ret = salt.utils.data.traverse_dict_and_list(__pillar__, key, {}, delimiter) if isinstance(ret, collections.Mapping) and \ isinstance(default, collections.Mapping): return salt.utils.dictupdate.update(default, ret) return salt.utils.data.traverse_dict_and_list( __pillar__, key, default, delimiter) def item(*args): ''' .. versionadded:: 0.16.2 Return one or more pillar entries CLI Examples: .. code-block:: bash salt '*' pillar.item foo salt '*' pillar.item foo bar baz ''' ret = {} for arg in args: try: ret[arg] = __pillar__[arg] except KeyError: pass return ret def raw(key=None): ''' Return the raw pillar data that is available in the module. This will show the pillar as it is loaded as the __pillar__ dict. CLI Example: .. code-block:: bash salt '*' pillar.raw With the optional key argument, you can select a subtree of the pillar raw data.:: salt '*' pillar.raw key='roles' ''' if key: ret = __pillar__.get(key, {}) else: ret = __pillar__ return ret # Allow pillar.data to also be used to return pillar data items = raw data = items
saltstack/salt
salt/states/boto_elasticsearch_domain.py
present
python
def present(name, DomainName, ElasticsearchClusterConfig=None, EBSOptions=None, AccessPolicies=None, SnapshotOptions=None, AdvancedOptions=None, Tags=None, region=None, key=None, keyid=None, profile=None, ElasticsearchVersion="1.5"): ''' Ensure domain exists. name The name of the state definition DomainName Name of the domain. ElasticsearchClusterConfig Configuration options for an Elasticsearch domain. Specifies the instance type and number of instances in the domain cluster. InstanceType (string) -- The instance type for an Elasticsearch cluster. InstanceCount (integer) -- The number of instances in the specified domain cluster. DedicatedMasterEnabled (boolean) -- A boolean value to indicate whether a dedicated master node is enabled. See About Dedicated Master Nodes for more information. ZoneAwarenessEnabled (boolean) -- A boolean value to indicate whether zone awareness is enabled. See About Zone Awareness for more information. DedicatedMasterType (string) -- The instance type for a dedicated master node. DedicatedMasterCount (integer) -- Total number of dedicated master nodes, active and on standby, for the cluster. EBSOptions Options to enable, disable and specify the type and size of EBS storage volumes. EBSEnabled (boolean) -- Specifies whether EBS-based storage is enabled. VolumeType (string) -- Specifies the volume type for EBS-based storage. VolumeSize (integer) -- Integer to specify the size of an EBS volume. Iops (integer) -- Specifies the IOPD for a Provisioned IOPS EBS volume (SSD). AccessPolicies IAM access policy SnapshotOptions Option to set time, in UTC format, of the daily automated snapshot. Default value is 0 hours. AutomatedSnapshotStartHour (integer) -- Specifies the time, in UTC format, when the service takes a daily automated snapshot of the specified Elasticsearch domain. Default value is 0 hours. AdvancedOptions Option to allow references to indices in an HTTP request body. Must be false when configuring access to individual sub-resources. By default, the value is true . region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ElasticsearchVersion String of format X.Y to specify version for the Elasticsearch domain eg. "1.5" or "2.3". ''' ret = {'name': DomainName, 'result': True, 'comment': '', 'changes': {} } if ElasticsearchClusterConfig is None: ElasticsearchClusterConfig = { 'DedicatedMasterEnabled': False, 'InstanceCount': 1, 'InstanceType': 'm3.medium.elasticsearch', 'ZoneAwarenessEnabled': False } if EBSOptions is None: EBSOptions = { 'EBSEnabled': False, } if SnapshotOptions is None: SnapshotOptions = { 'AutomatedSnapshotStartHour': 0 } if AdvancedOptions is None: AdvancedOptions = { 'rest.action.multi.allow_explicit_index': 'true' } if Tags is None: Tags = {} if AccessPolicies is not None and isinstance(AccessPolicies, six.string_types): try: AccessPolicies = salt.utils.json.loads(AccessPolicies) except ValueError as e: ret['result'] = False ret['comment'] = 'Failed to create domain: {0}.'.format(e.message) return ret r = __salt__['boto_elasticsearch_domain.exists'](DomainName=DomainName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create domain: {0}.'.format(r['error']['message']) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'Domain {0} is set to be created.'.format(DomainName) ret['result'] = None return ret r = __salt__['boto_elasticsearch_domain.create'](DomainName=DomainName, ElasticsearchClusterConfig=ElasticsearchClusterConfig, EBSOptions=EBSOptions, AccessPolicies=AccessPolicies, SnapshotOptions=SnapshotOptions, AdvancedOptions=AdvancedOptions, ElasticsearchVersion=str(ElasticsearchVersion), # future lint: disable=blacklisted-function region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create domain: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_elasticsearch_domain.describe'](DomainName, region=region, key=key, keyid=keyid, profile=profile) ret['changes']['old'] = {'domain': None} ret['changes']['new'] = _describe ret['comment'] = 'Domain {0} created.'.format(DomainName) return ret ret['comment'] = os.linesep.join([ret['comment'], 'Domain {0} is present.'.format(DomainName)]) ret['changes'] = {} # domain exists, ensure config matches _status = __salt__['boto_elasticsearch_domain.status'](DomainName=DomainName, region=region, key=key, keyid=keyid, profile=profile)['domain'] if _status.get('ElasticsearchVersion') != str(ElasticsearchVersion): # future lint: disable=blacklisted-function ret['result'] = False ret['comment'] = ( 'Failed to update domain: version cannot be modified ' 'from {0} to {1}.'.format( _status.get('ElasticsearchVersion'), str(ElasticsearchVersion) # future lint: disable=blacklisted-function ) ) return ret _describe = __salt__['boto_elasticsearch_domain.describe'](DomainName=DomainName, region=region, key=key, keyid=keyid, profile=profile)['domain'] _describe['AccessPolicies'] = salt.utils.json.loads(_describe['AccessPolicies']) # When EBSEnabled is false, describe returns extra values that can't be set if not _describe.get('EBSOptions', {}).get('EBSEnabled'): opts = _describe.get('EBSOptions', {}) opts.pop('VolumeSize', None) opts.pop('VolumeType', None) comm_args = {} need_update = False es_opts = {'ElasticsearchClusterConfig': ElasticsearchClusterConfig, 'EBSOptions': EBSOptions, 'AccessPolicies': AccessPolicies, 'SnapshotOptions': SnapshotOptions, 'AdvancedOptions': AdvancedOptions} for k, v in six.iteritems(es_opts): if not _compare_json(v, _describe[k]): need_update = True comm_args[k] = v ret['changes'].setdefault('new', {})[k] = v ret['changes'].setdefault('old', {})[k] = _describe[k] if need_update: if __opts__['test']: msg = 'Domain {0} set to be modified.'.format(DomainName) ret['comment'] = msg ret['result'] = None return ret ret['comment'] = os.linesep.join([ret['comment'], 'Domain to be modified']) r = __salt__['boto_elasticsearch_domain.update'](DomainName=DomainName, region=region, key=key, keyid=keyid, profile=profile, **comm_args) if not r.get('updated'): ret['result'] = False ret['comment'] = 'Failed to update domain: {0}.'.format(r['error']) ret['changes'] = {} return ret return ret
Ensure domain exists. name The name of the state definition DomainName Name of the domain. ElasticsearchClusterConfig Configuration options for an Elasticsearch domain. Specifies the instance type and number of instances in the domain cluster. InstanceType (string) -- The instance type for an Elasticsearch cluster. InstanceCount (integer) -- The number of instances in the specified domain cluster. DedicatedMasterEnabled (boolean) -- A boolean value to indicate whether a dedicated master node is enabled. See About Dedicated Master Nodes for more information. ZoneAwarenessEnabled (boolean) -- A boolean value to indicate whether zone awareness is enabled. See About Zone Awareness for more information. DedicatedMasterType (string) -- The instance type for a dedicated master node. DedicatedMasterCount (integer) -- Total number of dedicated master nodes, active and on standby, for the cluster. EBSOptions Options to enable, disable and specify the type and size of EBS storage volumes. EBSEnabled (boolean) -- Specifies whether EBS-based storage is enabled. VolumeType (string) -- Specifies the volume type for EBS-based storage. VolumeSize (integer) -- Integer to specify the size of an EBS volume. Iops (integer) -- Specifies the IOPD for a Provisioned IOPS EBS volume (SSD). AccessPolicies IAM access policy SnapshotOptions Option to set time, in UTC format, of the daily automated snapshot. Default value is 0 hours. AutomatedSnapshotStartHour (integer) -- Specifies the time, in UTC format, when the service takes a daily automated snapshot of the specified Elasticsearch domain. Default value is 0 hours. AdvancedOptions Option to allow references to indices in an HTTP request body. Must be false when configuring access to individual sub-resources. By default, the value is true . region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ElasticsearchVersion String of format X.Y to specify version for the Elasticsearch domain eg. "1.5" or "2.3".
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elasticsearch_domain.py#L106-L325
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "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 _compare_json(current, desired):\n return __utils__['boto3.json_objs_equal'](current, desired)\n" ]
# -*- coding: utf-8 -*- ''' Manage Elasticsearch Domains ============================ .. versionadded:: 2016.11.0 Create and destroy Elasticsearch domains. Be aware that this interacts with Amazon's services, and so may incur charges. This module uses ``boto3``, which can be installed via package, or pip. This module accepts explicit vpc credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More information available `here <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html>`_. If IAM roles are not used you need to specify them either in a pillar file or in the minion's config file: .. code-block:: yaml vpc.keyid: GKTADJGHEIQSXMKKRBJ08H vpc.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs It's also possible to specify ``key``, ``keyid`` and ``region`` via a profile, either passed in as a dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 .. code-block:: yaml Ensure domain exists: boto_elasticsearch_domain.present: - DomainName: mydomain - profile='user-credentials' - ElasticsearchVersion: "2.3" - ElasticsearchClusterConfig: InstanceType": "t2.micro.elasticsearch" InstanceCount: 1 DedicatedMasterEnabled: False ZoneAwarenessEnabled: False - EBSOptions: EBSEnabled: True VolumeType: "gp2" VolumeSize: 10 Iops: 0 - AccessPolicies: Version: "2012-10-17" Statement: - Effect: "Allow" - Principal: AWS: "*" - Action: - "es:*" - Resource: "arn:aws:es:*:111111111111:domain/mydomain/*" - Condition: IpAddress: "aws:SourceIp": - "127.0.0.1" - "127.0.0.2" - SnapshotOptions: AutomatedSnapshotStartHour: 0 - AdvancedOptions: rest.action.multi.allow_explicit_index": "true" - Tags: a: "b" - region: us-east-1 - keyid: GKTADJGHEIQSXMKKRBJ08H - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging import os # Import Salt libs import salt.utils.json # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto is available. ''' return 'boto_elasticsearch_domain' if 'boto_elasticsearch_domain.exists' in __salt__ else False def _compare_json(current, desired): return __utils__['boto3.json_objs_equal'](current, desired) def absent(name, DomainName, region=None, key=None, keyid=None, profile=None): ''' Ensure domain with passed properties is absent. name The name of the state definition. DomainName Name of the domain. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': DomainName, 'result': True, 'comment': '', 'changes': {} } r = __salt__['boto_elasticsearch_domain.exists'](DomainName, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to delete domain: {0}.'.format(r['error']['message']) return ret if r and not r['exists']: ret['comment'] = 'Domain {0} does not exist.'.format(DomainName) return ret if __opts__['test']: ret['comment'] = 'Domain {0} is set to be removed.'.format(DomainName) ret['result'] = None return ret r = __salt__['boto_elasticsearch_domain.delete'](DomainName, region=region, key=key, keyid=keyid, profile=profile) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete domain: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = {'domain': DomainName} ret['changes']['new'] = {'domain': None} ret['comment'] = 'Domain {0} deleted.'.format(DomainName) return ret
saltstack/salt
salt/modules/inspectlib/dbhandle.py
DBHandleBase.open
python
def open(self, new=False): ''' Init the database, if required. ''' self._db.new() if new else self._db.open() # pylint: disable=W0106 self._run_init_queries()
Init the database, if required.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/dbhandle.py#L39-L44
[ "def _run_init_queries(self):\n '''\n Initialization queries\n '''\n for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):\n self._db.create_table_from_object(obj())\n", "def new(self):\n '''\n Create a new database and opens it.\n\n :return:\n '''\n dbname = self._label()\n self.db_path = os.path.join(self.path, dbname)\n if not os.path.exists(self.db_path):\n os.makedirs(self.db_path)\n self._opened = True\n self.list_tables()\n\n return dbname\n", "def open(self, dbname=None):\n '''\n Open database from the path with the name or latest.\n If there are no yet databases, create a new implicitly.\n\n :return:\n '''\n databases = self.list()\n if self.is_closed():\n self.db_path = os.path.join(self.path, dbname or (databases and databases[0] or self.new()))\n if not self._opened:\n self.list_tables()\n self._opened = True\n" ]
class DBHandleBase(object): ''' Handle for the *volatile* database, which serves the purpose of caching the inspected data. This database can be destroyed or corrupted, so it should be simply re-created from scratch. ''' def __init__(self, path): ''' Constructor. ''' self._path = path self.init_queries = list() self._db = CsvDB(self._path) def _run_init_queries(self): ''' Initialization queries ''' for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir): self._db.create_table_from_object(obj()) def purge(self): ''' Purge whole database. ''' for table_name in self._db.list_tables(): self._db.flush(table_name) self._run_init_queries() def flush(self, table): ''' Flush the table. ''' self._db.flush(table) def close(self): ''' Close the database connection. ''' self._db.close() def __getattr__(self, item): ''' Proxy methods from the Database instance. :param item: :return: ''' return getattr(self._db, item)
saltstack/salt
salt/modules/inspectlib/dbhandle.py
DBHandleBase._run_init_queries
python
def _run_init_queries(self): ''' Initialization queries ''' for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir): self._db.create_table_from_object(obj())
Initialization queries
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/dbhandle.py#L46-L51
[ "def create_table_from_object(self, obj):\n '''\n Create a table from the object.\n NOTE: This method doesn't stores anything.\n\n :param obj:\n :return:\n '''\n get_type = lambda item: str(type(item)).split(\"'\")[1]\n if not os.path.exists(os.path.join(self.db_path, obj._TABLE)):\n with gzip.open(os.path.join(self.db_path, obj._TABLE), 'wb') as table_file:\n csv.writer(table_file).writerow(['{col}:{type}'.format(col=elm[0], type=get_type(elm[1]))\n for elm in tuple(obj.__dict__.items())])\n self._tables[obj._TABLE] = self._load_table(obj._TABLE)\n" ]
class DBHandleBase(object): ''' Handle for the *volatile* database, which serves the purpose of caching the inspected data. This database can be destroyed or corrupted, so it should be simply re-created from scratch. ''' def __init__(self, path): ''' Constructor. ''' self._path = path self.init_queries = list() self._db = CsvDB(self._path) def open(self, new=False): ''' Init the database, if required. ''' self._db.new() if new else self._db.open() # pylint: disable=W0106 self._run_init_queries() def purge(self): ''' Purge whole database. ''' for table_name in self._db.list_tables(): self._db.flush(table_name) self._run_init_queries() def flush(self, table): ''' Flush the table. ''' self._db.flush(table) def close(self): ''' Close the database connection. ''' self._db.close() def __getattr__(self, item): ''' Proxy methods from the Database instance. :param item: :return: ''' return getattr(self._db, item)
saltstack/salt
salt/modules/inspectlib/dbhandle.py
DBHandleBase.purge
python
def purge(self): ''' Purge whole database. ''' for table_name in self._db.list_tables(): self._db.flush(table_name) self._run_init_queries()
Purge whole database.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/dbhandle.py#L53-L60
[ "def _run_init_queries(self):\n '''\n Initialization queries\n '''\n for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):\n self._db.create_table_from_object(obj())\n", "def flush(self, table):\n '''\n Flush table.\n\n :param table:\n :return:\n '''\n table_path = os.path.join(self.db_path, table)\n if os.path.exists(table_path):\n os.unlink(table_path)\n", "def list_tables(self):\n '''\n Load existing tables and their descriptions.\n\n :return:\n '''\n if not self._tables:\n for table_name in os.listdir(self.db_path):\n self._tables[table_name] = self._load_table(table_name)\n\n return self._tables.keys()\n" ]
class DBHandleBase(object): ''' Handle for the *volatile* database, which serves the purpose of caching the inspected data. This database can be destroyed or corrupted, so it should be simply re-created from scratch. ''' def __init__(self, path): ''' Constructor. ''' self._path = path self.init_queries = list() self._db = CsvDB(self._path) def open(self, new=False): ''' Init the database, if required. ''' self._db.new() if new else self._db.open() # pylint: disable=W0106 self._run_init_queries() def _run_init_queries(self): ''' Initialization queries ''' for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir): self._db.create_table_from_object(obj()) def flush(self, table): ''' Flush the table. ''' self._db.flush(table) def close(self): ''' Close the database connection. ''' self._db.close() def __getattr__(self, item): ''' Proxy methods from the Database instance. :param item: :return: ''' return getattr(self._db, item)
saltstack/salt
salt/modules/github.py
_get_config_value
python
def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value
Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L69-L97
null
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
_get_client
python
def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key]
Return the GitHub client, cached into __context__ for performance
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L100-L115
[ "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
list_users
python
def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key]
List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L162-L189
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def _get_members(organization, params=None):\n return github.PaginatedList.PaginatedList(\n github.NamedUser.NamedUser,\n organization._requester,\n organization.url + \"/members\",\n params\n )\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_user
python
def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response
Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L192-L256
[ "def list_users(profile=\"github\", ignore_cache=False):\n '''\n List all users within the organization.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n ignore_cache\n Bypasses the use of cached users.\n\n .. versionadded:: 2016.11.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.list_users\n salt myminion github.list_users profile='my-github-profile'\n '''\n org_name = _get_config_value(profile, 'org_name')\n key = \"github.{0}:users\".format(\n org_name\n )\n if key not in __context__ or ignore_cache:\n client = _get_client(profile)\n organization = client.get_organization(org_name)\n __context__[key] = [member.login for member in _get_members(organization, None)]\n return __context__[key]\n", "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
add_user
python
def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending'
Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L259-L292
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
remove_user
python
def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user)
Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L295-L326
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_issue
python
def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret
Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L329-L374
[ "def _query(profile,\n action=None,\n command=None,\n args=None,\n method='GET',\n header_dict=None,\n data=None,\n url='https://api.github.com/',\n per_page=None):\n '''\n Make a web call to the GitHub API and deal with paginated results.\n '''\n if not isinstance(args, dict):\n args = {}\n\n if action:\n url += action\n\n if command:\n url += '/{0}'.format(command)\n\n log.debug('GitHub URL: %s', url)\n\n if 'access_token' not in args.keys():\n args['access_token'] = _get_config_value(profile, 'token')\n if per_page and 'per_page' not in args.keys():\n args['per_page'] = per_page\n\n if header_dict is None:\n header_dict = {}\n\n if method != 'POST':\n header_dict['Accept'] = 'application/json'\n\n decode = True\n if method == 'DELETE':\n decode = False\n\n # GitHub paginates all queries when returning many items.\n # Gather all data using multiple queries and handle pagination.\n complete_result = []\n next_page = True\n page_number = ''\n while next_page is True:\n if page_number:\n args['page'] = page_number\n result = salt.utils.http.query(url,\n method,\n params=args,\n data=data,\n header_dict=header_dict,\n decode=decode,\n decode_type='json',\n headers=True,\n status=True,\n text=True,\n hide_fields=['access_token'],\n opts=__opts__,\n )\n log.debug('GitHub Response Status Code: %s',\n result['status'])\n\n if result['status'] == 200:\n if isinstance(result['dict'], dict):\n # If only querying for one item, such as a single issue\n # The GitHub API returns a single dictionary, instead of\n # A list of dictionaries. In that case, we can return.\n return result['dict']\n\n complete_result = complete_result + result['dict']\n else:\n raise CommandExecutionError(\n 'GitHub Response Error: {0}'.format(result.get('error'))\n )\n\n try:\n link_info = result.get('headers').get('Link').split(',')[0]\n except AttributeError:\n # Only one page of data was returned; exit the loop.\n next_page = False\n continue\n\n if 'next' in link_info:\n # Get the 'next' page number from the Link header.\n page_number = link_info.split('>')[0].split('&page=')[1]\n else:\n # Last page already processed; break the loop.\n next_page = False\n\n return complete_result\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def _format_issue(issue):\n '''\n Helper function to format API return information into a more manageable\n and useful dictionary for issue information.\n\n issue\n The issue to format.\n '''\n ret = {'id': issue.get('id'),\n 'issue_number': issue.get('number'),\n 'state': issue.get('state'),\n 'title': issue.get('title'),\n 'user': issue.get('user').get('login'),\n 'html_url': issue.get('html_url')}\n\n assignee = issue.get('assignee')\n if assignee:\n assignee = assignee.get('login')\n\n labels = issue.get('labels')\n label_names = []\n for label in labels:\n label_names.append(label.get('name'))\n\n milestone = issue.get('milestone')\n if milestone:\n milestone = milestone.get('title')\n\n ret['assignee'] = assignee\n ret['labels'] = label_names\n ret['milestone'] = milestone\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_issue_comments
python
def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret
Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L377-L437
[ "def _query(profile,\n action=None,\n command=None,\n args=None,\n method='GET',\n header_dict=None,\n data=None,\n url='https://api.github.com/',\n per_page=None):\n '''\n Make a web call to the GitHub API and deal with paginated results.\n '''\n if not isinstance(args, dict):\n args = {}\n\n if action:\n url += action\n\n if command:\n url += '/{0}'.format(command)\n\n log.debug('GitHub URL: %s', url)\n\n if 'access_token' not in args.keys():\n args['access_token'] = _get_config_value(profile, 'token')\n if per_page and 'per_page' not in args.keys():\n args['per_page'] = per_page\n\n if header_dict is None:\n header_dict = {}\n\n if method != 'POST':\n header_dict['Accept'] = 'application/json'\n\n decode = True\n if method == 'DELETE':\n decode = False\n\n # GitHub paginates all queries when returning many items.\n # Gather all data using multiple queries and handle pagination.\n complete_result = []\n next_page = True\n page_number = ''\n while next_page is True:\n if page_number:\n args['page'] = page_number\n result = salt.utils.http.query(url,\n method,\n params=args,\n data=data,\n header_dict=header_dict,\n decode=decode,\n decode_type='json',\n headers=True,\n status=True,\n text=True,\n hide_fields=['access_token'],\n opts=__opts__,\n )\n log.debug('GitHub Response Status Code: %s',\n result['status'])\n\n if result['status'] == 200:\n if isinstance(result['dict'], dict):\n # If only querying for one item, such as a single issue\n # The GitHub API returns a single dictionary, instead of\n # A list of dictionaries. In that case, we can return.\n return result['dict']\n\n complete_result = complete_result + result['dict']\n else:\n raise CommandExecutionError(\n 'GitHub Response Error: {0}'.format(result.get('error'))\n )\n\n try:\n link_info = result.get('headers').get('Link').split(',')[0]\n except AttributeError:\n # Only one page of data was returned; exit the loop.\n next_page = False\n continue\n\n if 'next' in link_info:\n # Get the 'next' page number from the Link header.\n page_number = link_info.split('>')[0].split('&page=')[1]\n else:\n # Last page already processed; break the loop.\n next_page = False\n\n return complete_result\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_issues
python
def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret
Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L440-L568
[ "def _query(profile,\n action=None,\n command=None,\n args=None,\n method='GET',\n header_dict=None,\n data=None,\n url='https://api.github.com/',\n per_page=None):\n '''\n Make a web call to the GitHub API and deal with paginated results.\n '''\n if not isinstance(args, dict):\n args = {}\n\n if action:\n url += action\n\n if command:\n url += '/{0}'.format(command)\n\n log.debug('GitHub URL: %s', url)\n\n if 'access_token' not in args.keys():\n args['access_token'] = _get_config_value(profile, 'token')\n if per_page and 'per_page' not in args.keys():\n args['per_page'] = per_page\n\n if header_dict is None:\n header_dict = {}\n\n if method != 'POST':\n header_dict['Accept'] = 'application/json'\n\n decode = True\n if method == 'DELETE':\n decode = False\n\n # GitHub paginates all queries when returning many items.\n # Gather all data using multiple queries and handle pagination.\n complete_result = []\n next_page = True\n page_number = ''\n while next_page is True:\n if page_number:\n args['page'] = page_number\n result = salt.utils.http.query(url,\n method,\n params=args,\n data=data,\n header_dict=header_dict,\n decode=decode,\n decode_type='json',\n headers=True,\n status=True,\n text=True,\n hide_fields=['access_token'],\n opts=__opts__,\n )\n log.debug('GitHub Response Status Code: %s',\n result['status'])\n\n if result['status'] == 200:\n if isinstance(result['dict'], dict):\n # If only querying for one item, such as a single issue\n # The GitHub API returns a single dictionary, instead of\n # A list of dictionaries. In that case, we can return.\n return result['dict']\n\n complete_result = complete_result + result['dict']\n else:\n raise CommandExecutionError(\n 'GitHub Response Error: {0}'.format(result.get('error'))\n )\n\n try:\n link_info = result.get('headers').get('Link').split(',')[0]\n except AttributeError:\n # Only one page of data was returned; exit the loop.\n next_page = False\n continue\n\n if 'next' in link_info:\n # Get the 'next' page number from the Link header.\n page_number = link_info.split('>')[0].split('&page=')[1]\n else:\n # Last page already processed; break the loop.\n next_page = False\n\n return complete_result\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def _format_issue(issue):\n '''\n Helper function to format API return information into a more manageable\n and useful dictionary for issue information.\n\n issue\n The issue to format.\n '''\n ret = {'id': issue.get('id'),\n 'issue_number': issue.get('number'),\n 'state': issue.get('state'),\n 'title': issue.get('title'),\n 'user': issue.get('user').get('login'),\n 'html_url': issue.get('html_url')}\n\n assignee = issue.get('assignee')\n if assignee:\n assignee = assignee.get('login')\n\n labels = issue.get('labels')\n label_names = []\n for label in labels:\n label_names.append(label.get('name'))\n\n milestone = issue.get('milestone')\n if milestone:\n milestone = milestone.get('title')\n\n ret['assignee'] = assignee\n ret['labels'] = label_names\n ret['milestone'] = milestone\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_milestones
python
def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret
Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L571-L650
[ "def _query(profile,\n action=None,\n command=None,\n args=None,\n method='GET',\n header_dict=None,\n data=None,\n url='https://api.github.com/',\n per_page=None):\n '''\n Make a web call to the GitHub API and deal with paginated results.\n '''\n if not isinstance(args, dict):\n args = {}\n\n if action:\n url += action\n\n if command:\n url += '/{0}'.format(command)\n\n log.debug('GitHub URL: %s', url)\n\n if 'access_token' not in args.keys():\n args['access_token'] = _get_config_value(profile, 'token')\n if per_page and 'per_page' not in args.keys():\n args['per_page'] = per_page\n\n if header_dict is None:\n header_dict = {}\n\n if method != 'POST':\n header_dict['Accept'] = 'application/json'\n\n decode = True\n if method == 'DELETE':\n decode = False\n\n # GitHub paginates all queries when returning many items.\n # Gather all data using multiple queries and handle pagination.\n complete_result = []\n next_page = True\n page_number = ''\n while next_page is True:\n if page_number:\n args['page'] = page_number\n result = salt.utils.http.query(url,\n method,\n params=args,\n data=data,\n header_dict=header_dict,\n decode=decode,\n decode_type='json',\n headers=True,\n status=True,\n text=True,\n hide_fields=['access_token'],\n opts=__opts__,\n )\n log.debug('GitHub Response Status Code: %s',\n result['status'])\n\n if result['status'] == 200:\n if isinstance(result['dict'], dict):\n # If only querying for one item, such as a single issue\n # The GitHub API returns a single dictionary, instead of\n # A list of dictionaries. In that case, we can return.\n return result['dict']\n\n complete_result = complete_result + result['dict']\n else:\n raise CommandExecutionError(\n 'GitHub Response Error: {0}'.format(result.get('error'))\n )\n\n try:\n link_info = result.get('headers').get('Link').split(',')[0]\n except AttributeError:\n # Only one page of data was returned; exit the loop.\n next_page = False\n continue\n\n if 'next' in link_info:\n # Get the 'next' page number from the Link header.\n page_number = link_info.split('>')[0].split('&page=')[1]\n else:\n # Last page already processed; break the loop.\n next_page = False\n\n return complete_result\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_milestone
python
def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret
Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L653-L723
[ "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_repo_info
python
def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key]
Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L752-L800
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def _repo_to_dict(repo):\n ret = {}\n ret['id'] = repo.id\n ret['name'] = repo.name\n ret['full_name'] = repo.full_name\n ret['owner'] = repo.owner.login\n ret['private'] = repo.private\n ret['html_url'] = repo.html_url\n ret['description'] = repo.description\n ret['fork'] = repo.fork\n ret['homepage'] = repo.homepage\n ret['size'] = repo.size\n ret['stargazers_count'] = repo.stargazers_count\n ret['watchers_count'] = repo.watchers_count\n ret['language'] = repo.language\n ret['open_issues_count'] = repo.open_issues_count\n ret['forks'] = repo.forks\n ret['open_issues'] = repo.open_issues\n ret['watchers'] = repo.watchers\n ret['default_branch'] = repo.default_branch\n ret['has_issues'] = repo.has_issues\n ret['has_wiki'] = repo.has_wiki\n ret['has_downloads'] = repo.has_downloads\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_repo_teams
python
def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret
Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L803-L846
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
list_private_repos
python
def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos
List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L870-L891
[ "def _get_repos(profile, params=None, ignore_cache=False):\n # Use cache when no params are given\n org_name = _get_config_value(profile, 'org_name')\n key = 'github.{0}:repos'.format(org_name)\n\n if key not in __context__ or ignore_cache or params is not None:\n org_name = _get_config_value(profile, 'org_name')\n client = _get_client(profile)\n organization = client.get_organization(org_name)\n\n result = github.PaginatedList.PaginatedList(\n github.Repository.Repository,\n organization._requester,\n organization.url + '/repos',\n params\n )\n\n # Only cache results if no params were given (full scan)\n if params is not None:\n return result\n\n next_result = []\n\n for repo in result:\n next_result.append(repo)\n\n # Cache a copy of each repo for single lookups\n repo_key = \"github.{0}:{1}:repo_info\".format(org_name, repo.name.lower())\n __context__[repo_key] = _repo_to_dict(repo)\n\n __context__[key] = next_result\n\n return __context__[key]\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
list_public_repos
python
def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos
List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L894-L914
[ "def _get_repos(profile, params=None, ignore_cache=False):\n # Use cache when no params are given\n org_name = _get_config_value(profile, 'org_name')\n key = 'github.{0}:repos'.format(org_name)\n\n if key not in __context__ or ignore_cache or params is not None:\n org_name = _get_config_value(profile, 'org_name')\n client = _get_client(profile)\n organization = client.get_organization(org_name)\n\n result = github.PaginatedList.PaginatedList(\n github.Repository.Repository,\n organization._requester,\n organization.url + '/repos',\n params\n )\n\n # Only cache results if no params were given (full scan)\n if params is not None:\n return result\n\n next_result = []\n\n for repo in result:\n next_result.append(repo)\n\n # Cache a copy of each repo for single lookups\n repo_key = \"github.{0}:{1}:repo_info\".format(org_name, repo.name.lower())\n __context__[repo_key] = _repo_to_dict(repo)\n\n __context__[key] = next_result\n\n return __context__[key]\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
add_repo
python
def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False
Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L917-L1002
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
edit_repo
python
def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False
Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1005-L1089
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_repo_info(repo_name, profile='github', ignore_cache=False):\n '''\n Return information for a given repo.\n\n .. versionadded:: 2016.11.0\n\n repo_name\n The name of the repository.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_repo_info salt\n salt myminion github.get_repo_info salt profile='my-github-profile'\n '''\n\n org_name = _get_config_value(profile, 'org_name')\n key = \"github.{0}:{1}:repo_info\".format(\n _get_config_value(profile, 'org_name'),\n repo_name.lower()\n )\n\n if key not in __context__ or ignore_cache:\n client = _get_client(profile)\n try:\n repo = client.get_repo('/'.join([org_name, repo_name]))\n if not repo:\n return {}\n\n # client.get_repo can return a github.Repository.Repository object,\n # even if the repo is invalid. We need to catch the exception when\n # we try to perform actions on the repo object, rather than above\n # the if statement.\n ret = _repo_to_dict(repo)\n\n __context__[key] = ret\n except github.UnknownObjectException:\n raise CommandExecutionError(\n 'The \\'{0}\\' repository under the \\'{1}\\' organization could not '\n 'be found.'.format(\n repo_name,\n org_name\n )\n )\n return __context__[key]\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
remove_repo
python
def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False
Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1092-L1125
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def _get_repos(profile, params=None, ignore_cache=False):\n # Use cache when no params are given\n org_name = _get_config_value(profile, 'org_name')\n key = 'github.{0}:repos'.format(org_name)\n\n if key not in __context__ or ignore_cache or params is not None:\n org_name = _get_config_value(profile, 'org_name')\n client = _get_client(profile)\n organization = client.get_organization(org_name)\n\n result = github.PaginatedList.PaginatedList(\n github.Repository.Repository,\n organization._requester,\n organization.url + '/repos',\n params\n )\n\n # Only cache results if no params were given (full scan)\n if params is not None:\n return result\n\n next_result = []\n\n for repo in result:\n next_result.append(repo)\n\n # Cache a copy of each repo for single lookups\n repo_key = \"github.{0}:{1}:repo_info\".format(org_name, repo.name.lower())\n __context__[repo_key] = _repo_to_dict(repo)\n\n __context__[key] = next_result\n\n return __context__[key]\n", "def get_repo_info(repo_name, profile='github', ignore_cache=False):\n '''\n Return information for a given repo.\n\n .. versionadded:: 2016.11.0\n\n repo_name\n The name of the repository.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_repo_info salt\n salt myminion github.get_repo_info salt profile='my-github-profile'\n '''\n\n org_name = _get_config_value(profile, 'org_name')\n key = \"github.{0}:{1}:repo_info\".format(\n _get_config_value(profile, 'org_name'),\n repo_name.lower()\n )\n\n if key not in __context__ or ignore_cache:\n client = _get_client(profile)\n try:\n repo = client.get_repo('/'.join([org_name, repo_name]))\n if not repo:\n return {}\n\n # client.get_repo can return a github.Repository.Repository object,\n # even if the repo is invalid. We need to catch the exception when\n # we try to perform actions on the repo object, rather than above\n # the if statement.\n ret = _repo_to_dict(repo)\n\n __context__[key] = ret\n except github.UnknownObjectException:\n raise CommandExecutionError(\n 'The \\'{0}\\' repository under the \\'{1}\\' organization could not '\n 'be found.'.format(\n repo_name,\n org_name\n )\n )\n return __context__[key]\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
add_team
python
def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False
Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1148-L1210
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def list_teams(profile=\"github\", ignore_cache=False):\n '''\n Lists all teams with the organization.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n ignore_cache\n Bypasses the use of cached teams.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.list_teams\n\n .. versionadded:: 2016.11.0\n '''\n key = 'github.{0}:teams'.format(\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__ or ignore_cache:\n client = _get_client(profile)\n organization = client.get_organization(\n _get_config_value(profile, 'org_name')\n )\n teams_data = organization.get_teams()\n teams = {}\n for team in teams_data:\n # Note that _rawData is used to access some properties here as they\n # are not exposed in older versions of PyGithub. It's VERY important\n # to use team._rawData instead of team.raw_data, as the latter forces\n # an API call to retrieve team details again.\n teams[team.name] = {\n 'id': team.id,\n 'slug': team.slug,\n 'description': team._rawData['description'],\n 'permission': team.permission,\n 'privacy': team._rawData['privacy']\n }\n __context__[key] = teams\n\n return __context__[key]\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
edit_team
python
def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False
Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1213-L1274
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
remove_team
python
def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False
Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1277-L1309
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n", "def list_teams(profile=\"github\", ignore_cache=False):\n '''\n Lists all teams with the organization.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n ignore_cache\n Bypasses the use of cached teams.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.list_teams\n\n .. versionadded:: 2016.11.0\n '''\n key = 'github.{0}:teams'.format(\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__ or ignore_cache:\n client = _get_client(profile)\n organization = client.get_organization(\n _get_config_value(profile, 'org_name')\n )\n teams_data = organization.get_teams()\n teams = {}\n for team in teams_data:\n # Note that _rawData is used to access some properties here as they\n # are not exposed in older versions of PyGithub. It's VERY important\n # to use team._rawData instead of team.raw_data, as the latter forces\n # an API call to retrieve team details again.\n teams[team.name] = {\n 'id': team.id,\n 'slug': team.slug,\n 'description': team._rawData['description'],\n 'permission': team.permission,\n 'privacy': team._rawData['privacy']\n }\n __context__[key] = teams\n\n return __context__[key]\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
list_team_repos
python
def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return []
Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1312-L1367
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
add_team_repo
python
def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True
Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1370-L1423
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n", "def list_team_repos(team_name, profile=\"github\", ignore_cache=False):\n '''\n Gets the repo details for a given team as a dict from repo_name to repo details.\n Note that repo names are always in lower case.\n\n team_name\n The name of the team from which to list repos.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n ignore_cache\n Bypasses the use of cached team repos.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.list_team_repos 'team_name'\n\n .. versionadded:: 2016.11.0\n '''\n cached_team = get_team(team_name, profile=profile)\n if not cached_team:\n log.error('Team %s does not exist.', team_name)\n return False\n\n # Return from cache if available\n if cached_team.get('repos') and not ignore_cache:\n return cached_team.get('repos')\n\n try:\n client = _get_client(profile)\n organization = client.get_organization(\n _get_config_value(profile, 'org_name')\n )\n team = organization.get_team(cached_team['id'])\n except UnknownObjectException:\n log.exception('Resource not found: %s', cached_team['id'])\n try:\n repos = {}\n for repo in team.get_repos():\n permission = 'pull'\n if repo.permissions.admin:\n permission = 'admin'\n elif repo.permissions.push:\n permission = 'push'\n\n repos[repo.name.lower()] = {\n 'permission': permission\n }\n cached_team['repos'] = repos\n return repos\n except UnknownObjectException:\n log.exception('Resource not found: %s', cached_team['id'])\n return []\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
remove_team_repo
python
def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True)
Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1426-L1462
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n", "def list_team_repos(team_name, profile=\"github\", ignore_cache=False):\n '''\n Gets the repo details for a given team as a dict from repo_name to repo details.\n Note that repo names are always in lower case.\n\n team_name\n The name of the team from which to list repos.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n ignore_cache\n Bypasses the use of cached team repos.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.list_team_repos 'team_name'\n\n .. versionadded:: 2016.11.0\n '''\n cached_team = get_team(team_name, profile=profile)\n if not cached_team:\n log.error('Team %s does not exist.', team_name)\n return False\n\n # Return from cache if available\n if cached_team.get('repos') and not ignore_cache:\n return cached_team.get('repos')\n\n try:\n client = _get_client(profile)\n organization = client.get_organization(\n _get_config_value(profile, 'org_name')\n )\n team = organization.get_team(cached_team['id'])\n except UnknownObjectException:\n log.exception('Resource not found: %s', cached_team['id'])\n try:\n repos = {}\n for repo in team.get_repos():\n permission = 'pull'\n if repo.permissions.admin:\n permission = 'admin'\n elif repo.permissions.push:\n permission = 'push'\n\n repos[repo.name.lower()] = {\n 'permission': permission\n }\n cached_team['repos'] = repos\n return repos\n except UnknownObjectException:\n log.exception('Resource not found: %s', cached_team['id'])\n return []\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
list_team_members
python
def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return []
Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1465-L1508
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
list_members_without_mfa
python
def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key]
List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1511-L1547
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def _get_members(organization, params=None):\n return github.PaginatedList.PaginatedList(\n github.NamedUser.NamedUser,\n organization._requester,\n organization.url + \"/members\",\n params\n )\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
is_team_member
python
def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile)
Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1550-L1572
[ "def list_team_members(team_name, profile=\"github\", ignore_cache=False):\n '''\n Gets the names of team members in lower case.\n\n team_name\n The name of the team from which to list members.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n ignore_cache\n Bypasses the use of cached team members.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.list_team_members 'team_name'\n\n .. versionadded:: 2016.11.0\n '''\n cached_team = get_team(team_name, profile=profile)\n if not cached_team:\n log.error('Team %s does not exist.', team_name)\n return False\n # Return from cache if available\n if cached_team.get('members') and not ignore_cache:\n return cached_team.get('members')\n\n try:\n client = _get_client(profile)\n organization = client.get_organization(\n _get_config_value(profile, 'org_name')\n )\n team = organization.get_team(cached_team['id'])\n except UnknownObjectException:\n log.exception('Resource not found: %s', cached_team['id'])\n try:\n cached_team['members'] = [member.login.lower()\n for member in team.get_members()]\n return cached_team['members']\n except UnknownObjectException:\n log.exception('Resource not found: %s', cached_team['id'])\n return []\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
add_team_member
python
def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True
Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1575-L1623
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
remove_team_member
python
def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member)
Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1626-L1668
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def get_team(name, profile=\"github\"):\n '''\n Returns the team details if a team with the given name exists, or None\n otherwise.\n\n name\n The team name for which to obtain information.\n\n profile\n The name of the profile configuration to use. Defaults to ``github``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt myminion github.get_team 'team_name'\n '''\n return list_teams(profile).get(name)\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
list_teams
python
def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key]
Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1671-L1714
[ "def _get_client(profile):\n '''\n Return the GitHub client, cached into __context__ for performance\n '''\n token = _get_config_value(profile, 'token')\n key = 'github.{0}:{1}'.format(\n token,\n _get_config_value(profile, 'org_name')\n )\n\n if key not in __context__:\n __context__[key] = github.Github(\n token,\n per_page=100\n )\n return __context__[key]\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
get_prs
python
def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret
Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1717-L1813
[ "def _query(profile,\n action=None,\n command=None,\n args=None,\n method='GET',\n header_dict=None,\n data=None,\n url='https://api.github.com/',\n per_page=None):\n '''\n Make a web call to the GitHub API and deal with paginated results.\n '''\n if not isinstance(args, dict):\n args = {}\n\n if action:\n url += action\n\n if command:\n url += '/{0}'.format(command)\n\n log.debug('GitHub URL: %s', url)\n\n if 'access_token' not in args.keys():\n args['access_token'] = _get_config_value(profile, 'token')\n if per_page and 'per_page' not in args.keys():\n args['per_page'] = per_page\n\n if header_dict is None:\n header_dict = {}\n\n if method != 'POST':\n header_dict['Accept'] = 'application/json'\n\n decode = True\n if method == 'DELETE':\n decode = False\n\n # GitHub paginates all queries when returning many items.\n # Gather all data using multiple queries and handle pagination.\n complete_result = []\n next_page = True\n page_number = ''\n while next_page is True:\n if page_number:\n args['page'] = page_number\n result = salt.utils.http.query(url,\n method,\n params=args,\n data=data,\n header_dict=header_dict,\n decode=decode,\n decode_type='json',\n headers=True,\n status=True,\n text=True,\n hide_fields=['access_token'],\n opts=__opts__,\n )\n log.debug('GitHub Response Status Code: %s',\n result['status'])\n\n if result['status'] == 200:\n if isinstance(result['dict'], dict):\n # If only querying for one item, such as a single issue\n # The GitHub API returns a single dictionary, instead of\n # A list of dictionaries. In that case, we can return.\n return result['dict']\n\n complete_result = complete_result + result['dict']\n else:\n raise CommandExecutionError(\n 'GitHub Response Error: {0}'.format(result.get('error'))\n )\n\n try:\n link_info = result.get('headers').get('Link').split(',')[0]\n except AttributeError:\n # Only one page of data was returned; exit the loop.\n next_page = False\n continue\n\n if 'next' in link_info:\n # Get the 'next' page number from the Link header.\n page_number = link_info.split('>')[0].split('&page=')[1]\n else:\n # Last page already processed; break the loop.\n next_page = False\n\n return complete_result\n", "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n", "def _format_pr(pr_):\n '''\n Helper function to format API return information into a more manageable\n and useful dictionary for pull request information.\n\n pr_\n The pull request to format.\n '''\n ret = {'id': pr_.get('id'),\n 'pr_number': pr_.get('number'),\n 'state': pr_.get('state'),\n 'title': pr_.get('title'),\n 'user': pr_.get('user').get('login'),\n 'html_url': pr_.get('html_url'),\n 'base_branch': pr_.get('base').get('ref')}\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
_format_pr
python
def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret
Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1816-L1832
null
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
_format_issue
python
def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret
Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1835-L1867
null
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
saltstack/salt
salt/modules/github.py
_query
python
def _query(profile, action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.github.com/', per_page=None): ''' Make a web call to the GitHub API and deal with paginated results. ''' if not isinstance(args, dict): args = {} if action: url += action if command: url += '/{0}'.format(command) log.debug('GitHub URL: %s', url) if 'access_token' not in args.keys(): args['access_token'] = _get_config_value(profile, 'token') if per_page and 'per_page' not in args.keys(): args['per_page'] = per_page if header_dict is None: header_dict = {} if method != 'POST': header_dict['Accept'] = 'application/json' decode = True if method == 'DELETE': decode = False # GitHub paginates all queries when returning many items. # Gather all data using multiple queries and handle pagination. complete_result = [] next_page = True page_number = '' while next_page is True: if page_number: args['page'] = page_number result = salt.utils.http.query(url, method, params=args, data=data, header_dict=header_dict, decode=decode, decode_type='json', headers=True, status=True, text=True, hide_fields=['access_token'], opts=__opts__, ) log.debug('GitHub Response Status Code: %s', result['status']) if result['status'] == 200: if isinstance(result['dict'], dict): # If only querying for one item, such as a single issue # The GitHub API returns a single dictionary, instead of # A list of dictionaries. In that case, we can return. return result['dict'] complete_result = complete_result + result['dict'] else: raise CommandExecutionError( 'GitHub Response Error: {0}'.format(result.get('error')) ) try: link_info = result.get('headers').get('Link').split(',')[0] except AttributeError: # Only one page of data was returned; exit the loop. next_page = False continue if 'next' in link_info: # Get the 'next' page number from the Link header. page_number = link_info.split('>')[0].split('&page=')[1] else: # Last page already processed; break the loop. next_page = False return complete_result
Make a web call to the GitHub API and deal with paginated results.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1870-L1959
[ "def _get_config_value(profile, config_name):\n '''\n Helper function that returns a profile's configuration value based on\n the supplied configuration name.\n\n profile\n The profile name that contains configuration information.\n\n config_name\n The configuration item's name to use to return configuration values.\n '''\n config = __salt__['config.option'](profile)\n if not config:\n raise CommandExecutionError(\n 'Authentication information could not be found for the '\n '\\'{0}\\' profile.'.format(profile)\n )\n\n config_value = config.get(config_name)\n if config_value is None:\n raise CommandExecutionError(\n 'The \\'{0}\\' parameter was not found in the \\'{1}\\' '\n 'profile.'.format(\n config_name,\n profile\n )\n )\n\n return config_value\n" ]
# -*- coding: utf-8 -*- ''' Module for interacting with the GitHub v3 API. .. versionadded:: 2016.3.0 :depends: PyGithub 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 'github' key by default, if defined. For example: .. code-block:: yaml github: token: abc1234 org_name: my_organization # optional: some functions require a repo_name, which # can be set in the config file, or passed in at the CLI. repo_name: my_repo # optional: it can be dangerous to change the privacy of a repository # in an automated way. set this to True to allow privacy modifications allow_repo_privacy_changes: False ''' # Import python libs from __future__ import absolute_import, unicode_literals, print_function import logging # Import Salt Libs from salt.exceptions import CommandExecutionError from salt.ext import six import salt.utils.http # Import third party libs HAS_LIBS = False try: import github import github.PaginatedList import github.NamedUser from github.GithubException import UnknownObjectException HAS_LIBS = True except ImportError: pass log = logging.getLogger(__name__) __virtualname__ = 'github' def __virtual__(): ''' Only load this module if PyGithub is installed on this minion. ''' if HAS_LIBS: return __virtualname__ return (False, 'The github execution module cannot be loaded: ' 'PyGithub library is not installed.') def _get_config_value(profile, config_name): ''' Helper function that returns a profile's configuration value based on the supplied configuration name. profile The profile name that contains configuration information. config_name The configuration item's name to use to return configuration values. ''' config = __salt__['config.option'](profile) if not config: raise CommandExecutionError( 'Authentication information could not be found for the ' '\'{0}\' profile.'.format(profile) ) config_value = config.get(config_name) if config_value is None: raise CommandExecutionError( 'The \'{0}\' parameter was not found in the \'{1}\' ' 'profile.'.format( config_name, profile ) ) return config_value def _get_client(profile): ''' Return the GitHub client, cached into __context__ for performance ''' token = _get_config_value(profile, 'token') key = 'github.{0}:{1}'.format( token, _get_config_value(profile, 'org_name') ) if key not in __context__: __context__[key] = github.Github( token, per_page=100 ) return __context__[key] def _get_members(organization, params=None): return github.PaginatedList.PaginatedList( github.NamedUser.NamedUser, organization._requester, organization.url + "/members", params ) def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, 'org_name') key = 'github.{0}:repos'.format(org_name) if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) organization = client.get_organization(org_name) result = github.PaginatedList.PaginatedList( github.Repository.Repository, organization._requester, organization.url + '/repos', params ) # Only cache results if no params were given (full scan) if params is not None: return result next_result = [] for repo in result: next_result.append(repo) # Cache a copy of each repo for single lookups repo_key = "github.{0}:{1}:repo_info".format(org_name, repo.name.lower()) __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result return __context__[key] def list_users(profile="github", ignore_cache=False): ''' List all users within the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached users. .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt myminion github.list_users salt myminion github.list_users profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:users".format( org_name ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) __context__[key] = [member.login for member in _get_members(organization, None)] return __context__[key] def get_user(name, profile='github', user_details=False): ''' Get a GitHub user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. user_details Prints user information details. Defaults to ``False``. If the user is already in the organization and user_details is set to False, the get_user function returns ``True``. If the user is not already present in the organization, user details will be printed by default. CLI Example: .. code-block:: bash salt myminion github.get_user github-handle salt myminion github.get_user github-handle user_details=true ''' if not user_details and name in list_users(profile): # User is in the org, no need for additional Data return True response = {} client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False response['company'] = user.company response['created_at'] = user.created_at response['email'] = user.email response['html_url'] = user.html_url response['id'] = user.id response['login'] = user.login response['name'] = user.name response['type'] = user.type response['url'] = user.url try: headers, data = organization._requester.requestJsonAndCheck( "GET", organization.url + "/memberships/" + user._identity ) except UnknownObjectException: response['membership_state'] = 'nonexistent' response['in_org'] = False return response response['in_org'] = organization.has_in_members(user) response['membership_state'] = data.get('state') return response def add_user(name, profile='github'): ''' Add a GitHub user. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: github_named_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False headers, data = organization._requester.requestJsonAndCheck( "PUT", organization.url + "/memberships/" + github_named_user._identity ) return data.get('state') == 'pending' def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user) def get_issue(issue_number, repo_name=None, profile='github', output='min'): ''' Return information about a single issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue to retrieve. repo_name The name of the repository from which to get the issue. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = 'issues/' + six.text_type(issue_number) ret = {} issue_data = _query(profile, action=action, command=command) issue_id = issue_data.get('id') if output == 'full': ret[issue_id] = issue_data else: ret[issue_id] = _format_issue(issue_data) return ret def get_issue_comments(issue_number, repo_name=None, profile='github', since=None, output='min'): ''' Return information about the comments for a given issue in a named repository. .. versionadded:: 2016.11.0 issue_number The number of the issue for which to retrieve comments. repo_name The name of the repository to which the issue belongs. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. since Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_issue_comments 514 salt myminion github.get_issue 514 repo_name=salt ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) command = '/'.join(['issues', six.text_type(issue_number), 'comments']) args = {} if since: args['since'] = since comments = _query(profile, action=action, command=command, args=args) ret = {} for comment in comments: comment_id = comment.get('id') if output == 'full': ret[comment_id] = comment else: ret[comment_id] = {'id': comment.get('id'), 'created_at': comment.get('created_at'), 'updated_at': comment.get('updated_at'), 'user_login': comment.get('user').get('login')} return ret def get_issues(repo_name=None, profile='github', milestone=None, state='open', assignee=None, creator=None, mentioned=None, labels=None, sort='created', direction='desc', since=None, output='min', per_page=None): ''' Returns information for all issues in a given repository, based on the search options. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. milestone The number of a GitHub milestone, or a string of either ``*`` or ``none``. If a number is passed, it should refer to a milestone by its number field. Use the ``github.get_milestone`` function to obtain a milestone's number. If the string ``*`` is passed, issues with any milestone are accepted. If the string ``none`` is passed, issues without milestones are returned. state Indicates the state of the issues to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. assignee Can be the name of a user. Pass in ``none`` (as a string) for issues with no assigned user or ``*`` for issues assigned to any user. creator The user that created the issue. mentioned A user that's mentioned in the issue. labels A string of comma separated label names. For example, ``bug,ui,@high``. sort What to sort results by. Can be either ``created``, ``updated``, or ``comments``. Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. since Only issues updated at or after this time are returned. This is a timestamp in ISO 8601 format: ``YYYY-MM-DDTHH:MM:SSZ``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_issues my-github-repo ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if milestone: args['milestone'] = milestone if assignee: args['assignee'] = assignee if creator: args['creator'] = creator if mentioned: args['mentioned'] = mentioned if labels: args['labels'] = labels if since: args['since'] = since if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} issues = _query(profile, action=action, command='issues', args=args) for issue in issues: # Pull requests are included in the issue list from GitHub # Let's not include those in the return. if issue.get('pull_request'): continue issue_id = issue.get('id') if output == 'full': ret[issue_id] = issue else: ret[issue_id] = _format_issue(issue) return ret def get_milestones(repo_name=None, profile='github', state='open', sort='due_on', direction='asc', output='min', per_page=None): ''' Return information about milestones for a given repository. .. versionadded:: 2016.11.0 repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state The state of the milestone. Either ``open``, ``closed``, or ``all``. Default is ``open``. sort What to sort results by. Either ``due_on`` or ``completeness``. Default is ``due_on``. direction The direction of the sort. Either ``asc`` or ``desc``. Default is ``asc``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of issues gathered from GitHub, per page. If not set, GitHub defaults are used. CLI Example: .. code-block:: bash salt myminion github.get_milestones ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'due_on': args['sort'] = sort if direction and direction != 'asc': args['direction'] = direction ret = {} milestones = _query(profile, action=action, command='milestones', args=args) for milestone in milestones: milestone_id = milestone.get('id') if output == 'full': ret[milestone_id] = milestone else: milestone.pop('creator') milestone.pop('html_url') milestone.pop('labels_url') ret[milestone_id] = milestone return ret def get_milestone(number=None, name=None, repo_name=None, profile='github', output='min'): ''' Return information about a single milestone in a named repository. .. versionadded:: 2016.11.0 number The number of the milestone to retrieve. If provided, this option will be favored over ``name``. name The name of the milestone to retrieve. repo_name The name of the repository for which to list issues. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the repo_name defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. output The amount of data returned by each issue. Defaults to ``min``. Change to ``full`` to see all issue output. CLI Example: .. code-block:: bash salt myminion github.get_milestone 72 salt myminion github.get_milestone name=my_milestone ''' ret = {} if not any([number, name]): raise CommandExecutionError( 'Either a milestone \'name\' or \'number\' must be provided.' ) org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) if number: command = 'milestones/' + six.text_type(number) milestone_data = _query(profile, action=action, command=command) milestone_id = milestone_data.get('id') if output == 'full': ret[milestone_id] = milestone_data else: milestone_data.pop('creator') milestone_data.pop('html_url') milestone_data.pop('labels_url') ret[milestone_id] = milestone_data return ret else: milestones = get_milestones(repo_name=repo_name, profile=profile, output=output) for key, val in six.iteritems(milestones): if val.get('title') == name: ret[key] = val return ret return ret def _repo_to_dict(repo): ret = {} ret['id'] = repo.id ret['name'] = repo.name ret['full_name'] = repo.full_name ret['owner'] = repo.owner.login ret['private'] = repo.private ret['html_url'] = repo.html_url ret['description'] = repo.description ret['fork'] = repo.fork ret['homepage'] = repo.homepage ret['size'] = repo.size ret['stargazers_count'] = repo.stargazers_count ret['watchers_count'] = repo.watchers_count ret['language'] = repo.language ret['open_issues_count'] = repo.open_issues_count ret['forks'] = repo.forks ret['open_issues'] = repo.open_issues ret['watchers'] = repo.watchers ret['default_branch'] = repo.default_branch ret['has_issues'] = repo.has_issues ret['has_wiki'] = repo.has_wiki ret['has_downloads'] = repo.has_downloads return ret def get_repo_info(repo_name, profile='github', ignore_cache=False): ''' Return information for a given repo. .. versionadded:: 2016.11.0 repo_name The name of the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_info salt salt myminion github.get_repo_info salt profile='my-github-profile' ''' org_name = _get_config_value(profile, 'org_name') key = "github.{0}:{1}:repo_info".format( _get_config_value(profile, 'org_name'), repo_name.lower() ) if key not in __context__ or ignore_cache: client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) if not repo: return {} # client.get_repo can return a github.Repository.Repository object, # even if the repo is invalid. We need to catch the exception when # we try to perform actions on the repo object, rather than above # the if statement. ret = _repo_to_dict(repo) __context__[key] = ret except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format( repo_name, org_name ) ) return __context__[key] def get_repo_teams(repo_name, profile='github'): ''' Return teams belonging to a repository. .. versionadded:: 2017.7.0 repo_name The name of the repository from which to retrieve teams. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_repo_teams salt salt myminion github.get_repo_teams salt profile='my-github-profile' ''' ret = [] org_name = _get_config_value(profile, 'org_name') client = _get_client(profile) try: repo = client.get_repo('/'.join([org_name, repo_name])) except github.UnknownObjectException: raise CommandExecutionError( 'The \'{0}\' repository under the \'{1}\' organization could not ' 'be found.'.format(repo_name, org_name) ) try: teams = repo.get_teams() for team in teams: ret.append({ 'id': team.id, 'name': team.name, 'permission': team.permission }) except github.UnknownObjectException: raise CommandExecutionError( 'Unable to retrieve teams for repository \'{0}\' under the \'{1}\' ' 'organization.'.format(repo_name, org_name) ) return ret def list_repos(profile='github'): ''' List all repositories within the organization. Includes public and private repositories within the organization Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_repos salt myminion github.list_repos profile='my-github-profile' ''' return [repo.name for repo in _get_repos(profile)] def list_private_repos(profile='github'): ''' List private repositories within the organization. Dependent upon the access rights of the profile token. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_private_repos salt myminion github.list_private_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is True: repos.append(repo.name) return repos def list_public_repos(profile='github'): ''' List public repositories within the organization. .. versionadded:: 2016.11.0 profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.list_public_repos salt myminion github.list_public_repos profile='my-github-profile' ''' repos = [] for repo in _get_repos(profile): if repo.private is False: repos.append(repo.name) return repos def add_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, auto_init=None, gitignore_template=None, license_template=None, profile="github"): ''' Create a new github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. auto_init Whether to create an initial commit with an empty README. gitignore_template The desired language or platform for a .gitignore, e.g "Haskell". license_template The desired LICENSE template to apply, e.g "mit" or "mozilla". profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads, 'auto_init': auto_init, 'gitignore_template': gitignore_template, 'license_template': license_template } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "POST", organization.url + "/repos", input=parameters ) return True except github.GithubException: log.exception('Error creating a repo') return False def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the team to be created. description The description of the repository. homepage The URL with more information about the repository. private The visiblity of the repository. Note that private repositories require a paid GitHub account. has_issues Whether to enable issues for this repository. has_wiki Whether to enable the wiki for this repository. has_downloads Whether to enable downloads for this repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_repo 'repo_name' .. versionadded:: 2016.11.0 ''' try: allow_private_change = _get_config_value(profile, 'allow_repo_privacy_changes') except CommandExecutionError: allow_private_change = False if private is not None and not allow_private_change: raise CommandExecutionError("The private field is set to be changed for " "repo {0} but allow_repo_privacy_changes " "disallows this.".format(name)) try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) given_params = { 'description': description, 'homepage': homepage, 'private': private, 'has_issues': has_issues, 'has_wiki': has_wiki, 'has_downloads': has_downloads } parameters = {'name': name} for param_name, param_value in six.iteritems(given_params): if param_value is not None: parameters[param_name] = param_value organization._requester.requestJsonAndCheck( "PATCH", repo.url, input=parameters ) get_repo_info(name, profile=profile, ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error editing a repo') return False def remove_repo(name, profile="github"): ''' Remove a Github repository. name The name of the repository to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_repo 'my-repo' .. versionadded:: 2016.11.0 ''' repo_info = get_repo_info(name, profile=profile) if not repo_info: log.error('Repo %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) repo = organization.get_repo(name) repo.delete() _get_repos(profile=profile, ignore_cache=True) # refresh cache return True except github.GithubException: log.exception('Error deleting a repo') return False def get_team(name, profile="github"): ''' Returns the team details if a team with the given name exists, or None otherwise. name The team name for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.get_team 'team_name' ''' return list_teams(profile).get(name) def add_team(name, description=None, repo_names=None, privacy=None, permission=None, profile="github"): ''' Create a new Github team within an organization. name The name of the team to be created. description The description of the team. repo_names The names of repositories to add the team to. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team 'team_name' .. versionadded:: 2016.11.0 ''' try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) parameters = {} parameters['name'] = name if description is not None: parameters['description'] = description if repo_names is not None: parameters['repo_names'] = repo_names if permission is not None: parameters['permission'] = permission if privacy is not None: parameters['privacy'] = privacy organization._requester.requestJsonAndCheck( 'POST', organization.url + '/teams', input=parameters ) list_teams(ignore_cache=True) # Refresh cache return True except github.GithubException: log.exception('Error creating a team') return False def edit_team(name, description=None, privacy=None, permission=None, profile="github"): ''' Updates an existing Github team. name The name of the team to be edited. description The description of the team. privacy The level of privacy for the team, can be 'secret' or 'closed'. permission The default permission for new repositories added to the team, can be 'pull', 'push' or 'admin'. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.edit_team 'team_name' description='Team description' .. versionadded:: 2016.11.0 ''' team = get_team(name, profile=profile) if not team: log.error('Team %s does not exist', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) parameters = {} if name is not None: parameters['name'] = name if description is not None: parameters['description'] = description if privacy is not None: parameters['privacy'] = privacy if permission is not None: parameters['permission'] = permission team._requester.requestJsonAndCheck( "PATCH", team.url, input=parameters ) return True except UnknownObjectException: log.exception('Resource not found') return False def remove_team(name, profile="github"): ''' Remove a github team. name The name of the team to be removed. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team 'team_name' .. versionadded:: 2016.11.0 ''' team_info = get_team(name, profile=profile) if not team_info: log.error('Team %s to be removed does not exist.', name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team_info['id']) team.delete() return list_teams(ignore_cache=True, profile=profile).get(name) is None except github.GithubException: log.exception('Error deleting a team') return False def list_team_repos(team_name, profile="github", ignore_cache=False): ''' Gets the repo details for a given team as a dict from repo_name to repo details. Note that repo names are always in lower case. team_name The name of the team from which to list repos. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_team_repos 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('repos') and not ignore_cache: return cached_team.get('repos') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: repos = {} for repo in team.get_repos(): permission = 'pull' if repo.permissions.admin: permission = 'admin' elif repo.permissions.push: permission = 'push' repos[repo.name.lower()] = { 'permission': permission } cached_team['repos'] = repos return repos except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def add_team_repo(repo_name, team_name, profile="github", permission=None): ''' Adds a repository to a team with team_name. repo_name The name of the repository to add. team_name The name of the team of which to add the repository. profile The name of the profile configuration to use. Defaults to ``github``. permission The permission for team members within the repository, can be 'pull', 'push' or 'admin'. If not specified, the default permission specified on the team will be used. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt myminion github.add_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False params = None if permission is not None: params = {'permission': permission} headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/repos/" + repo._identity, input=params ) # Try to refresh cache list_team_repos(team_name, profile=profile, ignore_cache=True) return True def remove_team_repo(repo_name, team_name, profile="github"): ''' Removes a repository from a team with team_name. repo_name The name of the repository to remove. team_name The name of the team of which to remove the repository. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_repo 'my_repo' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) repo = organization.get_repo(repo_name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False team.remove_from_repos(repo) return repo_name not in list_team_repos(team_name, profile=profile, ignore_cache=True) def list_team_members(team_name, profile="github", ignore_cache=False): ''' Gets the names of team members in lower case. team_name The name of the team from which to list members. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team members. CLI Example: .. code-block:: bash salt myminion github.list_team_members 'team_name' .. versionadded:: 2016.11.0 ''' cached_team = get_team(team_name, profile=profile) if not cached_team: log.error('Team %s does not exist.', team_name) return False # Return from cache if available if cached_team.get('members') and not ignore_cache: return cached_team.get('members') try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(cached_team['id']) except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) try: cached_team['members'] = [member.login.lower() for member in team.get_members()] return cached_team['members'] except UnknownObjectException: log.exception('Resource not found: %s', cached_team['id']) return [] def list_members_without_mfa(profile="github", ignore_cache=False): ''' List all members (in lower case) without MFA turned on. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached team repos. CLI Example: .. code-block:: bash salt myminion github.list_members_without_mfa .. versionadded:: 2016.11.0 ''' key = "github.{0}:non_mfa_users".format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) filter_key = 'filter' # Silly hack to see if we're past PyGithub 1.26.0, where the name of # the filter kwarg changed if hasattr(github.Team.Team, 'membership'): filter_key = 'filter_' __context__[key] = [m.login.lower() for m in _get_members(organization, {filter_key: '2fa_disabled'})] return __context__[key] def is_team_member(name, team_name, profile="github"): ''' Returns True if the github user is in the team with team_name, or False otherwise. name The name of the user whose membership to check. team_name The name of the team to check membership in. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.is_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' return name.lower() in list_team_members(team_name, profile=profile) def add_team_member(name, team_name, profile="github"): ''' Adds a team member to a team with team_name. name The name of the team member to add. team_name The name of the team of which to add the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.add_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False try: # Can't use team.add_membership due to this bug that hasn't made it into # a PyGithub release yet https://github.com/PyGithub/PyGithub/issues/363 headers, data = team._requester.requestJsonAndCheck( "PUT", team.url + "/memberships/" + member._identity, input={'role': 'member'}, parameters={'role': 'member'} ) except github.GithubException: log.exception('Error in adding a member to a team') return False return True def remove_team_member(name, team_name, profile="github"): ''' Removes a team member from a team with team_name. name The name of the team member to remove. team_name The name of the team from which to remove the user. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_team_member 'user_name' 'team_name' .. versionadded:: 2016.11.0 ''' team = get_team(team_name, profile=profile) if not team: log.error('Team %s does not exist', team_name) return False try: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) team = organization.get_team(team['id']) member = client.get_user(name) except UnknownObjectException: log.exception('Resource not found: %s', team['id']) return False if not hasattr(team, 'remove_from_members'): return (False, 'PyGithub 1.26.0 or greater is required for team ' 'management, please upgrade.') team.remove_from_members(member) return not team.has_in_members(member) def list_teams(profile="github", ignore_cache=False): ''' Lists all teams with the organization. profile The name of the profile configuration to use. Defaults to ``github``. ignore_cache Bypasses the use of cached teams. CLI Example: .. code-block:: bash salt myminion github.list_teams .. versionadded:: 2016.11.0 ''' key = 'github.{0}:teams'.format( _get_config_value(profile, 'org_name') ) if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) teams_data = organization.get_teams() teams = {} for team in teams_data: # Note that _rawData is used to access some properties here as they # are not exposed in older versions of PyGithub. It's VERY important # to use team._rawData instead of team.raw_data, as the latter forces # an API call to retrieve team details again. teams[team.name] = { 'id': team.id, 'slug': team.slug, 'description': team._rawData['description'], 'permission': team.permission, 'privacy': team._rawData['privacy'] } __context__[key] = teams return __context__[key] def get_prs(repo_name=None, profile='github', state='open', head=None, base=None, sort='created', direction='desc', output='min', per_page=None): ''' Returns information for all pull requests in a given repository, based on the search options provided. .. versionadded:: 2017.7.0 repo_name The name of the repository for which to list pull requests. This argument is required, either passed via the CLI, or defined in the configured profile. A ``repo_name`` passed as a CLI argument will override the ``repo_name`` defined in the configured profile, if provided. profile The name of the profile configuration to use. Defaults to ``github``. state Indicates the state of the pull requests to return. Can be either ``open``, ``closed``, or ``all``. Default is ``open``. head Filter pull requests by head user and branch name in the format of ``user:ref-name``. Example: ``'github:new-script-format'``. Default is ``None``. base Filter pulls by base branch name. Example: ``gh-pages``. Default is ``None``. sort What to sort results by. Can be either ``created``, ``updated``, ``popularity`` (comment count), or ``long-running`` (age, filtering by pull requests updated within the last month). Default is ``created``. direction The direction of the sort. Can be either ``asc`` or ``desc``. Default is ``desc``. output The amount of data returned by each pull request. Defaults to ``min``. Change to ``full`` to see all pull request output. per_page GitHub paginates data in their API calls. Use this value to increase or decrease the number of pull requests gathered from GitHub, per page. If not set, GitHub defaults are used. Maximum is 100. CLI Example: .. code-block:: bash salt myminion github.get_prs salt myminion github.get_prs base=2016.11 ''' org_name = _get_config_value(profile, 'org_name') if repo_name is None: repo_name = _get_config_value(profile, 'repo_name') action = '/'.join(['repos', org_name, repo_name]) args = {} # Build API arguments, as necessary. if head: args['head'] = head if base: args['base'] = base if per_page: args['per_page'] = per_page # Only pass the following API args if they're not the defaults listed. if state and state != 'open': args['state'] = state if sort and sort != 'created': args['sort'] = sort if direction and direction != 'desc': args['direction'] = direction ret = {} prs = _query(profile, action=action, command='pulls', args=args) for pr_ in prs: pr_id = pr_.get('id') if output == 'full': ret[pr_id] = pr_ else: ret[pr_id] = _format_pr(pr_) return ret def _format_pr(pr_): ''' Helper function to format API return information into a more manageable and useful dictionary for pull request information. pr_ The pull request to format. ''' ret = {'id': pr_.get('id'), 'pr_number': pr_.get('number'), 'state': pr_.get('state'), 'title': pr_.get('title'), 'user': pr_.get('user').get('login'), 'html_url': pr_.get('html_url'), 'base_branch': pr_.get('base').get('ref')} return ret def _format_issue(issue): ''' Helper function to format API return information into a more manageable and useful dictionary for issue information. issue The issue to format. ''' ret = {'id': issue.get('id'), 'issue_number': issue.get('number'), 'state': issue.get('state'), 'title': issue.get('title'), 'user': issue.get('user').get('login'), 'html_url': issue.get('html_url')} assignee = issue.get('assignee') if assignee: assignee = assignee.get('login') labels = issue.get('labels') label_names = [] for label in labels: label_names.append(label.get('name')) milestone = issue.get('milestone') if milestone: milestone = milestone.get('title') ret['assignee'] = assignee ret['labels'] = label_names ret['milestone'] = milestone return ret
saltstack/salt
salt/states/snapper.py
_get_baseline_from_tag
python
def _get_baseline_from_tag(config, tag): ''' Returns the last created baseline snapshot marked with `tag` ''' last_snapshot = None for snapshot in __salt__['snapper.list_snapshots'](config): if tag == snapshot['userdata'].get("baseline_tag"): if not last_snapshot or last_snapshot['timestamp'] < snapshot['timestamp']: last_snapshot = snapshot return last_snapshot
Returns the last created baseline snapshot marked with `tag`
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/snapper.py#L122-L131
null
# -*- coding: utf-8 -*- ''' Managing implicit state and baselines using snapshots ===================================================== .. versionadded:: 2016.11.0 Salt can manage state against explicitly defined state, for example if your minion state is defined by: .. code-block:: yaml /etc/config_file: file.managed: - source: salt://configs/myconfig If someone modifies this file, the next application of the highstate will allow the admin to correct this deviation and the file will be corrected. Now, what happens if somebody creates a file ``/etc/new_config_file`` and deletes ``/etc/important_config_file``? Unless you have a explicit rule, this change will go unnoticed. The snapper state module allows you to manage state implicitly, in addition to explicit rules, in order to define a baseline and iterate with explicit rules as they show that they work in production. The workflow is: once you have a working and audited system, you would create your baseline snapshot (eg. with ``salt tgt snapper.create_snapshot``) and define in your state this baseline using the identifier of the snapshot (in this case: 20): .. code-block:: yaml my_baseline: snapper.baseline_snapshot: - number: 20 - include_diff: False - ignore: - /var/log - /var/cache Baseline snapshots can be also referenced by tag. Most recent baseline snapshot is used in case of multiple snapshots with the same tag: my_baseline_external_storage: snapper.baseline_snapshot: - tag: my_custom_baseline_tag - config: external - ignore: - /mnt/tmp_files/ If you have this state, and you haven't done changes to the system since the snapshot, and you add a user, the state will show you the changes (including full diffs) to ``/etc/passwd``, ``/etc/shadow``, etc if you call it with ``test=True`` and will undo all changes if you call it without. This allows you to add more explicit state knowing that you are starting from a very well defined state, and that you can audit any change that is not part of your explicit configuration. So after you made this your state, you decided to introduce a change in your configuration: .. code-block:: yaml my_baseline: snapper.baseline_snapshot: - number: 20 - ignore: - /var/log - /var/cache hosts_entry: file.blockreplace: - name: /etc/hosts - content: 'First line of content' - append_if_not_found: True The change in ``/etc/hosts`` will be done after any other change that deviates from the specified snapshot are reverted. This could be for example, modifications to the ``/etc/passwd`` file or changes in the ``/etc/hosts`` that could render your the ``hosts_entry`` rule void or dangerous. Once you take a new snapshot and you update the baseline snapshot number to include the change in ``/etc/hosts`` the ``hosts_entry`` rule will basically do nothing. You are free to leave it there for documentation, to ensure that the change is made in case the snapshot is wrong, but if you remove anything that comes after the ``snapper.baseline_snapshot`` as it will have no effect; by the moment the state is evaluated, the baseline state was already applied and include this change. .. warning:: Make sure you specify the baseline state before other rules, otherwise the baseline state will revert all changes if they are not present in the snapshot. .. warning:: Do not specify more than one baseline rule as only the last one will affect the result. :codeauthor: Duncan Mac-Vicar P. <dmacvicar@suse.de> :codeauthor: Pablo Suárez Hernández <psuarezhernandez@suse.de> :maturity: new :platform: Linux ''' from __future__ import absolute_import, unicode_literals, print_function import os def __virtual__(): ''' Only load if the snapper module is available in __salt__ ''' return 'snapper' if 'snapper.diff' in __salt__ else False def baseline_snapshot(name, number=None, tag=None, include_diff=True, config='root', ignore=None): ''' Enforces that no file is modified comparing against a previously defined snapshot identified by number. number Number of selected baseline snapshot. tag Tag of the selected baseline snapshot. Most recent baseline baseline snapshot is used in case of multiple snapshots with the same tag. (`tag` and `number` cannot be used at the same time) include_diff Include a diff in the response (Default: True) config Snapper config name (Default: root) ignore List of files to ignore. (Default: None) ''' if not ignore: ignore = [] ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if number is None and tag is None: ret.update({'result': False, 'comment': 'Snapshot tag or number must be specified'}) return ret if number and tag: ret.update({'result': False, 'comment': 'Cannot use snapshot tag and number at the same time'}) return ret if tag: snapshot = _get_baseline_from_tag(config, tag) if not snapshot: ret.update({'result': False, 'comment': 'Baseline tag "{0}" not found'.format(tag)}) return ret number = snapshot['id'] status = __salt__['snapper.status']( config, num_pre=0, num_post=number) for target in ignore: if os.path.isfile(target): status.pop(target, None) elif os.path.isdir(target): for target_file in [target_file for target_file in status.keys() if target_file.startswith(target)]: status.pop(target_file, None) for file in status: # Only include diff for modified files if "modified" in status[file]["status"] and include_diff: status[file].pop("status") status[file].update(__salt__['snapper.diff'](config, num_pre=0, num_post=number, filename=file).get(file, {})) if __opts__['test'] and status: ret['changes'] = status ret['comment'] = "{0} files changes are set to be undone".format(len(status.keys())) ret['result'] = None elif __opts__['test'] and not status: ret['changes'] = {} ret['comment'] = "Nothing to be done" ret['result'] = True elif not __opts__['test'] and status: undo = __salt__['snapper.undo'](config, num_pre=number, num_post=0, files=status.keys()) ret['changes']['sumary'] = undo ret['changes']['files'] = status ret['result'] = True else: ret['comment'] = "No changes were done" ret['result'] = True return ret
saltstack/salt
salt/states/snapper.py
baseline_snapshot
python
def baseline_snapshot(name, number=None, tag=None, include_diff=True, config='root', ignore=None): ''' Enforces that no file is modified comparing against a previously defined snapshot identified by number. number Number of selected baseline snapshot. tag Tag of the selected baseline snapshot. Most recent baseline baseline snapshot is used in case of multiple snapshots with the same tag. (`tag` and `number` cannot be used at the same time) include_diff Include a diff in the response (Default: True) config Snapper config name (Default: root) ignore List of files to ignore. (Default: None) ''' if not ignore: ignore = [] ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} if number is None and tag is None: ret.update({'result': False, 'comment': 'Snapshot tag or number must be specified'}) return ret if number and tag: ret.update({'result': False, 'comment': 'Cannot use snapshot tag and number at the same time'}) return ret if tag: snapshot = _get_baseline_from_tag(config, tag) if not snapshot: ret.update({'result': False, 'comment': 'Baseline tag "{0}" not found'.format(tag)}) return ret number = snapshot['id'] status = __salt__['snapper.status']( config, num_pre=0, num_post=number) for target in ignore: if os.path.isfile(target): status.pop(target, None) elif os.path.isdir(target): for target_file in [target_file for target_file in status.keys() if target_file.startswith(target)]: status.pop(target_file, None) for file in status: # Only include diff for modified files if "modified" in status[file]["status"] and include_diff: status[file].pop("status") status[file].update(__salt__['snapper.diff'](config, num_pre=0, num_post=number, filename=file).get(file, {})) if __opts__['test'] and status: ret['changes'] = status ret['comment'] = "{0} files changes are set to be undone".format(len(status.keys())) ret['result'] = None elif __opts__['test'] and not status: ret['changes'] = {} ret['comment'] = "Nothing to be done" ret['result'] = True elif not __opts__['test'] and status: undo = __salt__['snapper.undo'](config, num_pre=number, num_post=0, files=status.keys()) ret['changes']['sumary'] = undo ret['changes']['files'] = status ret['result'] = True else: ret['comment'] = "No changes were done" ret['result'] = True return ret
Enforces that no file is modified comparing against a previously defined snapshot identified by number. number Number of selected baseline snapshot. tag Tag of the selected baseline snapshot. Most recent baseline baseline snapshot is used in case of multiple snapshots with the same tag. (`tag` and `number` cannot be used at the same time) include_diff Include a diff in the response (Default: True) config Snapper config name (Default: root) ignore List of files to ignore. (Default: None)
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/snapper.py#L134-L219
[ "def _get_baseline_from_tag(config, tag):\n '''\n Returns the last created baseline snapshot marked with `tag`\n '''\n last_snapshot = None\n for snapshot in __salt__['snapper.list_snapshots'](config):\n if tag == snapshot['userdata'].get(\"baseline_tag\"):\n if not last_snapshot or last_snapshot['timestamp'] < snapshot['timestamp']:\n last_snapshot = snapshot\n return last_snapshot\n" ]
# -*- coding: utf-8 -*- ''' Managing implicit state and baselines using snapshots ===================================================== .. versionadded:: 2016.11.0 Salt can manage state against explicitly defined state, for example if your minion state is defined by: .. code-block:: yaml /etc/config_file: file.managed: - source: salt://configs/myconfig If someone modifies this file, the next application of the highstate will allow the admin to correct this deviation and the file will be corrected. Now, what happens if somebody creates a file ``/etc/new_config_file`` and deletes ``/etc/important_config_file``? Unless you have a explicit rule, this change will go unnoticed. The snapper state module allows you to manage state implicitly, in addition to explicit rules, in order to define a baseline and iterate with explicit rules as they show that they work in production. The workflow is: once you have a working and audited system, you would create your baseline snapshot (eg. with ``salt tgt snapper.create_snapshot``) and define in your state this baseline using the identifier of the snapshot (in this case: 20): .. code-block:: yaml my_baseline: snapper.baseline_snapshot: - number: 20 - include_diff: False - ignore: - /var/log - /var/cache Baseline snapshots can be also referenced by tag. Most recent baseline snapshot is used in case of multiple snapshots with the same tag: my_baseline_external_storage: snapper.baseline_snapshot: - tag: my_custom_baseline_tag - config: external - ignore: - /mnt/tmp_files/ If you have this state, and you haven't done changes to the system since the snapshot, and you add a user, the state will show you the changes (including full diffs) to ``/etc/passwd``, ``/etc/shadow``, etc if you call it with ``test=True`` and will undo all changes if you call it without. This allows you to add more explicit state knowing that you are starting from a very well defined state, and that you can audit any change that is not part of your explicit configuration. So after you made this your state, you decided to introduce a change in your configuration: .. code-block:: yaml my_baseline: snapper.baseline_snapshot: - number: 20 - ignore: - /var/log - /var/cache hosts_entry: file.blockreplace: - name: /etc/hosts - content: 'First line of content' - append_if_not_found: True The change in ``/etc/hosts`` will be done after any other change that deviates from the specified snapshot are reverted. This could be for example, modifications to the ``/etc/passwd`` file or changes in the ``/etc/hosts`` that could render your the ``hosts_entry`` rule void or dangerous. Once you take a new snapshot and you update the baseline snapshot number to include the change in ``/etc/hosts`` the ``hosts_entry`` rule will basically do nothing. You are free to leave it there for documentation, to ensure that the change is made in case the snapshot is wrong, but if you remove anything that comes after the ``snapper.baseline_snapshot`` as it will have no effect; by the moment the state is evaluated, the baseline state was already applied and include this change. .. warning:: Make sure you specify the baseline state before other rules, otherwise the baseline state will revert all changes if they are not present in the snapshot. .. warning:: Do not specify more than one baseline rule as only the last one will affect the result. :codeauthor: Duncan Mac-Vicar P. <dmacvicar@suse.de> :codeauthor: Pablo Suárez Hernández <psuarezhernandez@suse.de> :maturity: new :platform: Linux ''' from __future__ import absolute_import, unicode_literals, print_function import os def __virtual__(): ''' Only load if the snapper module is available in __salt__ ''' return 'snapper' if 'snapper.diff' in __salt__ else False def _get_baseline_from_tag(config, tag): ''' Returns the last created baseline snapshot marked with `tag` ''' last_snapshot = None for snapshot in __salt__['snapper.list_snapshots'](config): if tag == snapshot['userdata'].get("baseline_tag"): if not last_snapshot or last_snapshot['timestamp'] < snapshot['timestamp']: last_snapshot = snapshot return last_snapshot
saltstack/salt
salt/utils/fsutils.py
_verify_run
python
def _verify_run(out, cmd=None): ''' Crash to the log if command execution was not successful. ''' if out.get('retcode', 0) and out['stderr']: if cmd: log.debug('Command: \'%s\'', cmd) log.debug('Return code: %s', out.get('retcode')) log.debug('Error output:\n%s', out.get('stderr', 'N/A')) raise CommandExecutionError(out['stderr'])
Crash to the log if command execution was not successful.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L25-L36
null
# -*- coding: utf-8 -*- ''' Run-time utilities ''' # # Copyright (C) 2014 SUSE LLC # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import re import os import logging # Import Salt libs import salt.utils.files from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def _get_mounts(fs_type=None): ''' List mounted filesystems. ''' mounts = {} with salt.utils.files.fopen('/proc/mounts') as fhr: for line in fhr.readlines(): line = salt.utils.stringutils.to_unicode(line) device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(" ") if fs_type and fstype != fs_type: continue if mounts.get(device) is None: mounts[device] = [] data = { 'mount_point': mntpnt, 'options': options.split(",") } if not fs_type: data['type'] = fstype mounts[device].append(data) return mounts # TODO: Due to "blkid -o export" strongly differs from system to system, this must go away in favor of _blkid() below! def _blkid_output(out, fs_type=None): ''' Parse blkid output. ''' flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split('\n\n')): dev = {} for items in flt(dev_meta.strip().split('\n')): key, val = items.split('=', 1) dev[key.lower()] = val if fs_type and dev.get('type', '') == fs_type or not fs_type: if 'type' in dev and fs_type: dev.pop('type') data[dev.pop('devname')] = dev if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data def _blkid(fs_type=None): ''' Return available media devices. :param fs_type: Filter only devices that are formatted by that file system. ''' flt = lambda data: [el for el in data if el.strip()] data = dict() for dev_meta in flt(os.popen("blkid -o full").read().split(os.linesep)): # No __salt__ around at this point. dev_meta = dev_meta.strip() if not dev_meta: continue device = dev_meta.split(" ") dev_name = device.pop(0)[:-1] data[dev_name] = dict() for k_set in device: ks_key, ks_value = [elm.replace('"', '') for elm in k_set.split("=")] data[dev_name][ks_key.lower()] = ks_value if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data def _is_device(path): ''' Return True if path is a physical device. ''' out = __salt__['cmd.run_all']('file -i {0}'.format(path)) _verify_run(out) # Always [device, mime, charset]. See (file --help) return re.split(r'\s+', out['stdout'])[1][:-1] == 'inode/blockdevice'
saltstack/salt
salt/utils/fsutils.py
_get_mounts
python
def _get_mounts(fs_type=None): ''' List mounted filesystems. ''' mounts = {} with salt.utils.files.fopen('/proc/mounts') as fhr: for line in fhr.readlines(): line = salt.utils.stringutils.to_unicode(line) device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(" ") if fs_type and fstype != fs_type: continue if mounts.get(device) is None: mounts[device] = [] data = { 'mount_point': mntpnt, 'options': options.split(",") } if not fs_type: data['type'] = fstype mounts[device].append(data) return mounts
List mounted filesystems.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L39-L60
[ "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", "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# -*- coding: utf-8 -*- ''' Run-time utilities ''' # # Copyright (C) 2014 SUSE LLC # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import re import os import logging # Import Salt libs import salt.utils.files from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def _verify_run(out, cmd=None): ''' Crash to the log if command execution was not successful. ''' if out.get('retcode', 0) and out['stderr']: if cmd: log.debug('Command: \'%s\'', cmd) log.debug('Return code: %s', out.get('retcode')) log.debug('Error output:\n%s', out.get('stderr', 'N/A')) raise CommandExecutionError(out['stderr']) # TODO: Due to "blkid -o export" strongly differs from system to system, this must go away in favor of _blkid() below! def _blkid_output(out, fs_type=None): ''' Parse blkid output. ''' flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split('\n\n')): dev = {} for items in flt(dev_meta.strip().split('\n')): key, val = items.split('=', 1) dev[key.lower()] = val if fs_type and dev.get('type', '') == fs_type or not fs_type: if 'type' in dev and fs_type: dev.pop('type') data[dev.pop('devname')] = dev if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data def _blkid(fs_type=None): ''' Return available media devices. :param fs_type: Filter only devices that are formatted by that file system. ''' flt = lambda data: [el for el in data if el.strip()] data = dict() for dev_meta in flt(os.popen("blkid -o full").read().split(os.linesep)): # No __salt__ around at this point. dev_meta = dev_meta.strip() if not dev_meta: continue device = dev_meta.split(" ") dev_name = device.pop(0)[:-1] data[dev_name] = dict() for k_set in device: ks_key, ks_value = [elm.replace('"', '') for elm in k_set.split("=")] data[dev_name][ks_key.lower()] = ks_value if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data def _is_device(path): ''' Return True if path is a physical device. ''' out = __salt__['cmd.run_all']('file -i {0}'.format(path)) _verify_run(out) # Always [device, mime, charset]. See (file --help) return re.split(r'\s+', out['stdout'])[1][:-1] == 'inode/blockdevice'
saltstack/salt
salt/utils/fsutils.py
_blkid_output
python
def _blkid_output(out, fs_type=None): ''' Parse blkid output. ''' flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split('\n\n')): dev = {} for items in flt(dev_meta.strip().split('\n')): key, val = items.split('=', 1) dev[key.lower()] = val if fs_type and dev.get('type', '') == fs_type or not fs_type: if 'type' in dev and fs_type: dev.pop('type') data[dev.pop('devname')] = dev if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data
Parse blkid output.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L64-L86
[ "def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n", "def _get_mounts(fs_type=None):\n '''\n List mounted filesystems.\n '''\n mounts = {}\n with salt.utils.files.fopen('/proc/mounts') as fhr:\n for line in fhr.readlines():\n line = salt.utils.stringutils.to_unicode(line)\n device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(\" \")\n if fs_type and fstype != fs_type:\n continue\n if mounts.get(device) is None:\n mounts[device] = []\n\n data = {\n 'mount_point': mntpnt,\n 'options': options.split(\",\")\n }\n if not fs_type:\n data['type'] = fstype\n mounts[device].append(data)\n return mounts\n", "flt = lambda data: [el for el in data if el.strip()]\n" ]
# -*- coding: utf-8 -*- ''' Run-time utilities ''' # # Copyright (C) 2014 SUSE LLC # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import re import os import logging # Import Salt libs import salt.utils.files from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def _verify_run(out, cmd=None): ''' Crash to the log if command execution was not successful. ''' if out.get('retcode', 0) and out['stderr']: if cmd: log.debug('Command: \'%s\'', cmd) log.debug('Return code: %s', out.get('retcode')) log.debug('Error output:\n%s', out.get('stderr', 'N/A')) raise CommandExecutionError(out['stderr']) def _get_mounts(fs_type=None): ''' List mounted filesystems. ''' mounts = {} with salt.utils.files.fopen('/proc/mounts') as fhr: for line in fhr.readlines(): line = salt.utils.stringutils.to_unicode(line) device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(" ") if fs_type and fstype != fs_type: continue if mounts.get(device) is None: mounts[device] = [] data = { 'mount_point': mntpnt, 'options': options.split(",") } if not fs_type: data['type'] = fstype mounts[device].append(data) return mounts # TODO: Due to "blkid -o export" strongly differs from system to system, this must go away in favor of _blkid() below! def _blkid(fs_type=None): ''' Return available media devices. :param fs_type: Filter only devices that are formatted by that file system. ''' flt = lambda data: [el for el in data if el.strip()] data = dict() for dev_meta in flt(os.popen("blkid -o full").read().split(os.linesep)): # No __salt__ around at this point. dev_meta = dev_meta.strip() if not dev_meta: continue device = dev_meta.split(" ") dev_name = device.pop(0)[:-1] data[dev_name] = dict() for k_set in device: ks_key, ks_value = [elm.replace('"', '') for elm in k_set.split("=")] data[dev_name][ks_key.lower()] = ks_value if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data def _is_device(path): ''' Return True if path is a physical device. ''' out = __salt__['cmd.run_all']('file -i {0}'.format(path)) _verify_run(out) # Always [device, mime, charset]. See (file --help) return re.split(r'\s+', out['stdout'])[1][:-1] == 'inode/blockdevice'
saltstack/salt
salt/utils/fsutils.py
_blkid
python
def _blkid(fs_type=None): ''' Return available media devices. :param fs_type: Filter only devices that are formatted by that file system. ''' flt = lambda data: [el for el in data if el.strip()] data = dict() for dev_meta in flt(os.popen("blkid -o full").read().split(os.linesep)): # No __salt__ around at this point. dev_meta = dev_meta.strip() if not dev_meta: continue device = dev_meta.split(" ") dev_name = device.pop(0)[:-1] data[dev_name] = dict() for k_set in device: ks_key, ks_value = [elm.replace('"', '') for elm in k_set.split("=")] data[dev_name][ks_key.lower()] = ks_value if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data
Return available media devices. :param fs_type: Filter only devices that are formatted by that file system.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L89-L114
null
# -*- coding: utf-8 -*- ''' Run-time utilities ''' # # Copyright (C) 2014 SUSE LLC # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import re import os import logging # Import Salt libs import salt.utils.files from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def _verify_run(out, cmd=None): ''' Crash to the log if command execution was not successful. ''' if out.get('retcode', 0) and out['stderr']: if cmd: log.debug('Command: \'%s\'', cmd) log.debug('Return code: %s', out.get('retcode')) log.debug('Error output:\n%s', out.get('stderr', 'N/A')) raise CommandExecutionError(out['stderr']) def _get_mounts(fs_type=None): ''' List mounted filesystems. ''' mounts = {} with salt.utils.files.fopen('/proc/mounts') as fhr: for line in fhr.readlines(): line = salt.utils.stringutils.to_unicode(line) device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(" ") if fs_type and fstype != fs_type: continue if mounts.get(device) is None: mounts[device] = [] data = { 'mount_point': mntpnt, 'options': options.split(",") } if not fs_type: data['type'] = fstype mounts[device].append(data) return mounts # TODO: Due to "blkid -o export" strongly differs from system to system, this must go away in favor of _blkid() below! def _blkid_output(out, fs_type=None): ''' Parse blkid output. ''' flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split('\n\n')): dev = {} for items in flt(dev_meta.strip().split('\n')): key, val = items.split('=', 1) dev[key.lower()] = val if fs_type and dev.get('type', '') == fs_type or not fs_type: if 'type' in dev and fs_type: dev.pop('type') data[dev.pop('devname')] = dev if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data def _is_device(path): ''' Return True if path is a physical device. ''' out = __salt__['cmd.run_all']('file -i {0}'.format(path)) _verify_run(out) # Always [device, mime, charset]. See (file --help) return re.split(r'\s+', out['stdout'])[1][:-1] == 'inode/blockdevice'
saltstack/salt
salt/utils/fsutils.py
_is_device
python
def _is_device(path): ''' Return True if path is a physical device. ''' out = __salt__['cmd.run_all']('file -i {0}'.format(path)) _verify_run(out) # Always [device, mime, charset]. See (file --help) return re.split(r'\s+', out['stdout'])[1][:-1] == 'inode/blockdevice'
Return True if path is a physical device.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L117-L125
[ "def _verify_run(out, cmd=None):\n '''\n Crash to the log if command execution was not successful.\n '''\n if out.get('retcode', 0) and out['stderr']:\n if cmd:\n log.debug('Command: \\'%s\\'', cmd)\n\n log.debug('Return code: %s', out.get('retcode'))\n log.debug('Error output:\\n%s', out.get('stderr', 'N/A'))\n\n raise CommandExecutionError(out['stderr'])\n" ]
# -*- coding: utf-8 -*- ''' Run-time utilities ''' # # Copyright (C) 2014 SUSE LLC # Import Python libs from __future__ import absolute_import, unicode_literals, print_function import re import os import logging # Import Salt libs import salt.utils.files from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six log = logging.getLogger(__name__) def _verify_run(out, cmd=None): ''' Crash to the log if command execution was not successful. ''' if out.get('retcode', 0) and out['stderr']: if cmd: log.debug('Command: \'%s\'', cmd) log.debug('Return code: %s', out.get('retcode')) log.debug('Error output:\n%s', out.get('stderr', 'N/A')) raise CommandExecutionError(out['stderr']) def _get_mounts(fs_type=None): ''' List mounted filesystems. ''' mounts = {} with salt.utils.files.fopen('/proc/mounts') as fhr: for line in fhr.readlines(): line = salt.utils.stringutils.to_unicode(line) device, mntpnt, fstype, options, fs_freq, fs_passno = line.strip().split(" ") if fs_type and fstype != fs_type: continue if mounts.get(device) is None: mounts[device] = [] data = { 'mount_point': mntpnt, 'options': options.split(",") } if not fs_type: data['type'] = fstype mounts[device].append(data) return mounts # TODO: Due to "blkid -o export" strongly differs from system to system, this must go away in favor of _blkid() below! def _blkid_output(out, fs_type=None): ''' Parse blkid output. ''' flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split('\n\n')): dev = {} for items in flt(dev_meta.strip().split('\n')): key, val = items.split('=', 1) dev[key.lower()] = val if fs_type and dev.get('type', '') == fs_type or not fs_type: if 'type' in dev and fs_type: dev.pop('type') data[dev.pop('devname')] = dev if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data def _blkid(fs_type=None): ''' Return available media devices. :param fs_type: Filter only devices that are formatted by that file system. ''' flt = lambda data: [el for el in data if el.strip()] data = dict() for dev_meta in flt(os.popen("blkid -o full").read().split(os.linesep)): # No __salt__ around at this point. dev_meta = dev_meta.strip() if not dev_meta: continue device = dev_meta.split(" ") dev_name = device.pop(0)[:-1] data[dev_name] = dict() for k_set in device: ks_key, ks_value = [elm.replace('"', '') for elm in k_set.split("=")] data[dev_name][ks_key.lower()] = ks_value if fs_type: mounts = _get_mounts(fs_type) for device in six.iterkeys(mounts): if data.get(device): data[device]['mounts'] = mounts[device] return data
saltstack/salt
salt/returners/mattermost_returner.py
returner
python
def returner(ret): ''' Send an mattermost message with the data ''' _options = _get_options(ret) api_url = _options.get('api_url') channel = _options.get('channel') username = _options.get('username') hook = _options.get('hook') if not hook: log.error('mattermost.hook not defined in salt config') return returns = ret.get('return') message = ('id: {0}\r\n' 'function: {1}\r\n' 'function args: {2}\r\n' 'jid: {3}\r\n' 'return: {4}\r\n').format( ret.get('id'), ret.get('fun'), ret.get('fun_args'), ret.get('jid'), returns) mattermost = post_message(channel, message, username, api_url, hook) return mattermost
Send an mattermost message with the data
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mattermost_returner.py#L96-L130
[ "def _get_options(ret=None):\n '''\n Get the mattermost options from salt.\n '''\n\n attrs = {'channel': 'channel',\n 'username': 'username',\n 'hook': 'hook',\n 'api_url': 'api_url'\n }\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n log.debug('Options: %s', _options)\n return _options\n", "def post_message(channel,\n message,\n username,\n api_url,\n hook):\n '''\n Send a message to a mattermost room.\n\n :param channel: The room name.\n :param message: The message to send to the mattermost room.\n :param username: Specify who the message is from.\n :param hook: The mattermost hook, if not specified in the configuration.\n :return: Boolean if message was sent successfully.\n '''\n\n parameters = dict()\n if channel:\n parameters['channel'] = channel\n if username:\n parameters['username'] = username\n parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text\n log.debug('Parameters: %s', parameters)\n result = salt.utils.mattermost.query(\n api_url=api_url,\n hook=hook,\n data=str('payload={0}').format(salt.utils.json.dumps(parameters))) # future lint: disable=blacklisted-function\n\n log.debug('result %s', result)\n return bool(result)\n" ]
# -*- coding: utf-8 -*- ''' Return salt data via mattermost .. versionadded:: 2017.7.0 The following fields can be set in the minion conf file: .. code-block:: yaml mattermost.hook (required) mattermost.username (optional) mattermost.channel (optional) Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml mattermost.channel mattermost.hook mattermost.username mattermost settings may also be configured as: .. code-block:: yaml mattermost: channel: RoomName hook: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx username: user To use the mattermost returner, append '--return mattermost' to the salt command. .. code-block:: bash salt '*' test.ping --return mattermost To override individual configuration items, append --return_kwargs '{'key:': 'value'}' to the salt command. .. code-block:: bash salt '*' test.ping --return mattermost --return_kwargs '{'channel': '#random'}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import 3rd-party libs from salt.ext import six # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.ext.six.moves.http_client # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import Salt Libs import salt.returners import salt.utils.json import salt.utils.mattermost log = logging.getLogger(__name__) __virtualname__ = 'mattermost' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' return __virtualname__ def _get_options(ret=None): ''' Get the mattermost options from salt. ''' attrs = {'channel': 'channel', 'username': 'username', 'hook': 'hook', 'api_url': 'api_url' } _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) log.debug('Options: %s', _options) return _options def event_return(events): ''' Send the events to a mattermost room. :param events: List of events :return: Boolean if messages were sent successfully. ''' _options = _get_options() api_url = _options.get('api_url') channel = _options.get('channel') username = _options.get('username') hook = _options.get('hook') is_ok = True for event in events: log.debug('Event: %s', event) log.debug('Event data: %s', event['data']) message = 'tag: {0}\r\n'.format(event['tag']) for key, value in six.iteritems(event['data']): message += '{0}: {1}\r\n'.format(key, value) result = post_message(channel, message, username, api_url, hook) if not result: is_ok = False return is_ok def post_message(channel, message, username, api_url, hook): ''' Send a message to a mattermost room. :param channel: The room name. :param message: The message to send to the mattermost room. :param username: Specify who the message is from. :param hook: The mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' parameters = dict() if channel: parameters['channel'] = channel if username: parameters['username'] = username parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text log.debug('Parameters: %s', parameters) result = salt.utils.mattermost.query( api_url=api_url, hook=hook, data=str('payload={0}').format(salt.utils.json.dumps(parameters))) # future lint: disable=blacklisted-function log.debug('result %s', result) return bool(result)
saltstack/salt
salt/returners/mattermost_returner.py
event_return
python
def event_return(events): ''' Send the events to a mattermost room. :param events: List of events :return: Boolean if messages were sent successfully. ''' _options = _get_options() api_url = _options.get('api_url') channel = _options.get('channel') username = _options.get('username') hook = _options.get('hook') is_ok = True for event in events: log.debug('Event: %s', event) log.debug('Event data: %s', event['data']) message = 'tag: {0}\r\n'.format(event['tag']) for key, value in six.iteritems(event['data']): message += '{0}: {1}\r\n'.format(key, value) result = post_message(channel, message, username, api_url, hook) if not result: is_ok = False return is_ok
Send the events to a mattermost room. :param events: List of events :return: Boolean if messages were sent successfully.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mattermost_returner.py#L133-L162
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _get_options(ret=None):\n '''\n Get the mattermost options from salt.\n '''\n\n attrs = {'channel': 'channel',\n 'username': 'username',\n 'hook': 'hook',\n 'api_url': 'api_url'\n }\n\n _options = salt.returners.get_returner_options(__virtualname__,\n ret,\n attrs,\n __salt__=__salt__,\n __opts__=__opts__)\n log.debug('Options: %s', _options)\n return _options\n", "def post_message(channel,\n message,\n username,\n api_url,\n hook):\n '''\n Send a message to a mattermost room.\n\n :param channel: The room name.\n :param message: The message to send to the mattermost room.\n :param username: Specify who the message is from.\n :param hook: The mattermost hook, if not specified in the configuration.\n :return: Boolean if message was sent successfully.\n '''\n\n parameters = dict()\n if channel:\n parameters['channel'] = channel\n if username:\n parameters['username'] = username\n parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text\n log.debug('Parameters: %s', parameters)\n result = salt.utils.mattermost.query(\n api_url=api_url,\n hook=hook,\n data=str('payload={0}').format(salt.utils.json.dumps(parameters))) # future lint: disable=blacklisted-function\n\n log.debug('result %s', result)\n return bool(result)\n" ]
# -*- coding: utf-8 -*- ''' Return salt data via mattermost .. versionadded:: 2017.7.0 The following fields can be set in the minion conf file: .. code-block:: yaml mattermost.hook (required) mattermost.username (optional) mattermost.channel (optional) Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml mattermost.channel mattermost.hook mattermost.username mattermost settings may also be configured as: .. code-block:: yaml mattermost: channel: RoomName hook: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx username: user To use the mattermost returner, append '--return mattermost' to the salt command. .. code-block:: bash salt '*' test.ping --return mattermost To override individual configuration items, append --return_kwargs '{'key:': 'value'}' to the salt command. .. code-block:: bash salt '*' test.ping --return mattermost --return_kwargs '{'channel': '#random'}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import 3rd-party libs from salt.ext import six # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.ext.six.moves.http_client # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import Salt Libs import salt.returners import salt.utils.json import salt.utils.mattermost log = logging.getLogger(__name__) __virtualname__ = 'mattermost' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' return __virtualname__ def _get_options(ret=None): ''' Get the mattermost options from salt. ''' attrs = {'channel': 'channel', 'username': 'username', 'hook': 'hook', 'api_url': 'api_url' } _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) log.debug('Options: %s', _options) return _options def returner(ret): ''' Send an mattermost message with the data ''' _options = _get_options(ret) api_url = _options.get('api_url') channel = _options.get('channel') username = _options.get('username') hook = _options.get('hook') if not hook: log.error('mattermost.hook not defined in salt config') return returns = ret.get('return') message = ('id: {0}\r\n' 'function: {1}\r\n' 'function args: {2}\r\n' 'jid: {3}\r\n' 'return: {4}\r\n').format( ret.get('id'), ret.get('fun'), ret.get('fun_args'), ret.get('jid'), returns) mattermost = post_message(channel, message, username, api_url, hook) return mattermost def post_message(channel, message, username, api_url, hook): ''' Send a message to a mattermost room. :param channel: The room name. :param message: The message to send to the mattermost room. :param username: Specify who the message is from. :param hook: The mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' parameters = dict() if channel: parameters['channel'] = channel if username: parameters['username'] = username parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text log.debug('Parameters: %s', parameters) result = salt.utils.mattermost.query( api_url=api_url, hook=hook, data=str('payload={0}').format(salt.utils.json.dumps(parameters))) # future lint: disable=blacklisted-function log.debug('result %s', result) return bool(result)
saltstack/salt
salt/returners/mattermost_returner.py
post_message
python
def post_message(channel, message, username, api_url, hook): ''' Send a message to a mattermost room. :param channel: The room name. :param message: The message to send to the mattermost room. :param username: Specify who the message is from. :param hook: The mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully. ''' parameters = dict() if channel: parameters['channel'] = channel if username: parameters['username'] = username parameters['text'] = '```' + message + '```' # pre-formatted, fixed-width text log.debug('Parameters: %s', parameters) result = salt.utils.mattermost.query( api_url=api_url, hook=hook, data=str('payload={0}').format(salt.utils.json.dumps(parameters))) # future lint: disable=blacklisted-function log.debug('result %s', result) return bool(result)
Send a message to a mattermost room. :param channel: The room name. :param message: The message to send to the mattermost room. :param username: Specify who the message is from. :param hook: The mattermost hook, if not specified in the configuration. :return: Boolean if message was sent successfully.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mattermost_returner.py#L165-L193
[ "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 query(hook=None,\n api_url=None,\n data=None):\n '''\n Mattermost object method function to construct and execute on the API URL.\n :param api_url: The Mattermost API URL\n :param hook: The Mattermost hook.\n :param data: The data to be sent for POST method.\n :return: The json response from the API call or False.\n '''\n method = 'POST'\n\n ret = {'message': '',\n 'res': True}\n\n base_url = _urljoin(api_url, '/hooks/')\n url = _urljoin(base_url, six.text_type(hook))\n\n result = salt.utils.http.query(url,\n method,\n data=data,\n decode=True,\n status=True)\n\n if result.get('status', None) == salt.ext.six.moves.http_client.OK:\n ret['message'] = 'Message posted {0} correctly'.format(data)\n return ret\n elif result.get('status', None) == salt.ext.six.moves.http_client.NO_CONTENT:\n return True\n else:\n log.debug(url)\n log.debug(data)\n log.debug(result)\n if 'dict' in result:\n _result = result['dict']\n if 'error' in _result:\n ret['message'] = result['error']\n ret['res'] = False\n return ret\n ret['message'] = 'Message not posted'\n else:\n ret['message'] = 'invalid_auth'\n ret['res'] = False\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Return salt data via mattermost .. versionadded:: 2017.7.0 The following fields can be set in the minion conf file: .. code-block:: yaml mattermost.hook (required) mattermost.username (optional) mattermost.channel (optional) Alternative configuration values can be used by prefacing the configuration. Any values not found in the alternative configuration will be pulled from the default location: .. code-block:: yaml mattermost.channel mattermost.hook mattermost.username mattermost settings may also be configured as: .. code-block:: yaml mattermost: channel: RoomName hook: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx username: user To use the mattermost returner, append '--return mattermost' to the salt command. .. code-block:: bash salt '*' test.ping --return mattermost To override individual configuration items, append --return_kwargs '{'key:': 'value'}' to the salt command. .. code-block:: bash salt '*' test.ping --return mattermost --return_kwargs '{'channel': '#random'}' ''' from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging # Import 3rd-party libs from salt.ext import six # pylint: disable=import-error,no-name-in-module,redefined-builtin import salt.ext.six.moves.http_client # pylint: enable=import-error,no-name-in-module,redefined-builtin # Import Salt Libs import salt.returners import salt.utils.json import salt.utils.mattermost log = logging.getLogger(__name__) __virtualname__ = 'mattermost' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' return __virtualname__ def _get_options(ret=None): ''' Get the mattermost options from salt. ''' attrs = {'channel': 'channel', 'username': 'username', 'hook': 'hook', 'api_url': 'api_url' } _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__) log.debug('Options: %s', _options) return _options def returner(ret): ''' Send an mattermost message with the data ''' _options = _get_options(ret) api_url = _options.get('api_url') channel = _options.get('channel') username = _options.get('username') hook = _options.get('hook') if not hook: log.error('mattermost.hook not defined in salt config') return returns = ret.get('return') message = ('id: {0}\r\n' 'function: {1}\r\n' 'function args: {2}\r\n' 'jid: {3}\r\n' 'return: {4}\r\n').format( ret.get('id'), ret.get('fun'), ret.get('fun_args'), ret.get('jid'), returns) mattermost = post_message(channel, message, username, api_url, hook) return mattermost def event_return(events): ''' Send the events to a mattermost room. :param events: List of events :return: Boolean if messages were sent successfully. ''' _options = _get_options() api_url = _options.get('api_url') channel = _options.get('channel') username = _options.get('username') hook = _options.get('hook') is_ok = True for event in events: log.debug('Event: %s', event) log.debug('Event data: %s', event['data']) message = 'tag: {0}\r\n'.format(event['tag']) for key, value in six.iteritems(event['data']): message += '{0}: {1}\r\n'.format(key, value) result = post_message(channel, message, username, api_url, hook) if not result: is_ok = False return is_ok
saltstack/salt
salt/modules/zookeeper.py
create
python
def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath)
Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L134-L187
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
ensure_path
python
def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls)
Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L190-L231
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
exists
python
def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path))
Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L234-L268
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
get
python
def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret)
Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L271-L306
[ "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n", "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
get_children
python
def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or []
Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L309-L344
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
set
python
def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version)
Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L347-L388
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
get_acls
python
def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0]
Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L391-L425
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
set_acls
python
def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version)
Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L428-L474
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
delete
python
def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive)
Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L477-L515
[ "def _get_zk_conn(profile=None, **connection_args):\n if profile:\n prefix = 'zookeeper:' + profile\n else:\n prefix = 'zookeeper'\n\n def get(key, default=None):\n '''\n look in connection_args first, then default to config file\n '''\n return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default)\n\n hosts = get('hosts', '127.0.0.1:2181')\n scheme = get('scheme', None)\n username = get('username', None)\n password = get('password', None)\n default_acl = get('default_acl', None)\n\n if isinstance(hosts, list):\n hosts = ','.join(hosts)\n\n if username is not None and password is not None and scheme is None:\n scheme = 'digest'\n\n auth_data = None\n if scheme and username and password:\n auth_data = [(scheme, ':'.join([username, password]))]\n\n if default_acl is not None:\n if isinstance(default_acl, list):\n default_acl = [make_digest_acl(**acl) for acl in default_acl]\n else:\n default_acl = [make_digest_acl(**default_acl)]\n\n __context__.setdefault('zkconnection', {}).setdefault(profile or hosts,\n kazoo.client.KazooClient(hosts=hosts,\n default_acl=default_acl,\n auth_data=auth_data))\n\n if not __context__['zkconnection'][profile or hosts].connected:\n __context__['zkconnection'][profile or hosts].start()\n\n return __context__['zkconnection'][profile or hosts]\n" ]
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
saltstack/salt
salt/modules/zookeeper.py
make_digest_acl
python
def make_digest_acl(username, password, read=False, write=False, create=False, delete=False, admin=False, allperms=False): ''' Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True ''' return kazoo.security.make_digest_acl(username, password, read, write, create, delete, admin, allperms)
Generate acl object .. note:: This is heavily used in the zookeeper state and probably is not useful as a cli module username username of acl password plain text password of acl read read acl write write acl create create acl delete delete acl admin admin acl allperms set all other acls to True CLI Example: .. code-block:: bash salt minion1 zookeeper.make_digest_acl username=daniel password=mypass allperms=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L518-L555
null
# -*- coding: utf-8 -*- ''' Zookeeper Module ~~~~~~~~~~~~~~~~ :maintainer: SaltStack :maturity: new :platform: all :depends: kazoo .. versionadded:: 2018.3.0 Configuration ============= :configuration: This module is not usable until the following are specified either in a pillar or in the minion's config file: .. code-block:: yaml zookeeper: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test If configuration for multiple zookeeper environments is required, they can be set up as different configuration profiles. For example: .. code-block:: yaml zookeeper: prod: hosts: zoo1,zoo2,zoo3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test dev: hosts: - dev1 - dev2 - dev3 default_acl: - username: daniel password: test read: true write: true create: true delete: true admin: true username: daniel password: test ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libraries try: import kazoo.client import kazoo.security HAS_KAZOO = True except ImportError: HAS_KAZOO = False # Import Salt libraries import salt.utils.stringutils __virtualname__ = 'zookeeper' def __virtual__(): if HAS_KAZOO: return __virtualname__ return False def _get_zk_conn(profile=None, **connection_args): if profile: prefix = 'zookeeper:' + profile else: prefix = 'zookeeper' def get(key, default=None): ''' look in connection_args first, then default to config file ''' return connection_args.get(key) or __salt__['config.get'](':'.join([prefix, key]), default) hosts = get('hosts', '127.0.0.1:2181') scheme = get('scheme', None) username = get('username', None) password = get('password', None) default_acl = get('default_acl', None) if isinstance(hosts, list): hosts = ','.join(hosts) if username is not None and password is not None and scheme is None: scheme = 'digest' auth_data = None if scheme and username and password: auth_data = [(scheme, ':'.join([username, password]))] if default_acl is not None: if isinstance(default_acl, list): default_acl = [make_digest_acl(**acl) for acl in default_acl] else: default_acl = [make_digest_acl(**default_acl)] __context__.setdefault('zkconnection', {}).setdefault(profile or hosts, kazoo.client.KazooClient(hosts=hosts, default_acl=default_acl, auth_data=auth_data)) if not __context__['zkconnection'][profile or hosts].connected: __context__['zkconnection'][profile or hosts].start() return __context__['zkconnection'][profile or hosts] def create(path, value='', acls=None, ephemeral=False, sequence=False, makepath=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Create Znode path path of znode to create value value to assign to znode (Default: '') acls list of acl dictionaries to be assigned (Default: None) ephemeral indicate node is ephemeral (Default: False) sequence indicate node is suffixed with a unique index (Default: False) makepath Create parent paths if they do not exist (Default: False) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.create /test/name daniel profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.create(path, salt.utils.stringutils.to_bytes(value), acls, ephemeral, sequence, makepath) def ensure_path(path, acls=None, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Ensure Znode path exists path Parent path to create acls list of acls dictionaries to be assigned (Default: None) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.ensure_path /test/name profile=prod ''' if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.ensure_path(path, acls) def exists(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Check if path exists path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.exists /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return bool(conn.exists(path)) def get(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret, _ = conn.get(path) return salt.utils.stringutils.to_str(ret) def get_children(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get children in znode path path path to check profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_children /test profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) ret = conn.get_children(path) return ret or [] def set(path, value, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Update znode with new value path znode to update value value to set in znode version only update znode if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set /test/name gtmanfred profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set(path, salt.utils.stringutils.to_bytes(value), version=version) def get_acls(path, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Get acls on a znode path path to znode profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.get_acls /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.get_acls(path)[0] def set_acls(path, acls, version=-1, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Set acls on a znode path path to znode acls list of acl dictionaries to set on the znode version only set acls if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.set_acls /test/name acls='[{"username": "gtmanfred", "password": "test", "all": True}]' profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if acls is None: acls = [] acls = [make_digest_acl(**acl) for acl in acls] conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.set_acls(path, acls, version) def delete(path, version=-1, recursive=False, profile=None, hosts=None, scheme=None, username=None, password=None, default_acl=None): ''' Delete znode path path to znode version only delete if version matches (Default: -1 (always matches)) profile Configured Zookeeper profile to authenticate with (Default: None) hosts Lists of Zookeeper Hosts (Default: '127.0.0.1:2181) scheme Scheme to authenticate with (Default: 'digest') username Username to authenticate (Default: None) password Password to authenticate (Default: None) default_acl Default acls to assign if a node is created in this connection (Default: None) CLI Example: .. code-block:: bash salt minion1 zookeeper.delete /test/name profile=prod ''' conn = _get_zk_conn(profile=profile, hosts=hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) return conn.delete(path, version, recursive)
saltstack/salt
salt/utils/mattermost.py
query
python
def query(hook=None, api_url=None, data=None): ''' Mattermost object method function to construct and execute on the API URL. :param api_url: The Mattermost API URL :param hook: The Mattermost hook. :param data: The data to be sent for POST method. :return: The json response from the API call or False. ''' method = 'POST' ret = {'message': '', 'res': True} base_url = _urljoin(api_url, '/hooks/') url = _urljoin(base_url, six.text_type(hook)) result = salt.utils.http.query(url, method, data=data, decode=True, status=True) if result.get('status', None) == salt.ext.six.moves.http_client.OK: ret['message'] = 'Message posted {0} correctly'.format(data) return ret elif result.get('status', None) == salt.ext.six.moves.http_client.NO_CONTENT: return True else: log.debug(url) log.debug(data) log.debug(result) if 'dict' in result: _result = result['dict'] if 'error' in _result: ret['message'] = result['error'] ret['res'] = False return ret ret['message'] = 'Message not posted' else: ret['message'] = 'invalid_auth' ret['res'] = False return ret
Mattermost object method function to construct and execute on the API URL. :param api_url: The Mattermost API URL :param hook: The Mattermost hook. :param data: The data to be sent for POST method. :return: The json response from the API call or False.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/mattermost.py#L29-L72
null
# -*- coding: utf-8 -*- ''' Library for interacting with Mattermost Incoming Webhooks :configuration: This module can be used by specifying the name of a configuration profile in the minion config, minion pillar, or master config. For example: .. code-block:: yaml mattermost: hook: 3tdgo8restnxiykdx88wqtxryr api_url: https://example.com ''' from __future__ import absolute_import, unicode_literals import logging # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.ext.six.moves.urllib.parse import urljoin as _urljoin import salt.ext.six.moves.http_client from salt.version import __version__ # pylint: enable=import-error,no-name-in-module import salt.utils.http from salt.ext import six log = logging.getLogger(__name__)
saltstack/salt
salt/pillar/confidant.py
ext_pillar
python
def ext_pillar(minion_id, pillar, profile=None): ''' Read pillar data from Confidant via its API. ''' if profile is None: profile = {} # default to returning failure ret = { 'credentials_result': False, 'credentials': None, 'credentials_metadata': None } profile_data = copy.deepcopy(profile) if profile_data.get('disabled', False): ret['result'] = True return ret token_version = profile_data.get('token_version', 1) try: url = profile_data['url'] auth_key = profile_data['auth_key'] auth_context = profile_data['auth_context'] role = auth_context['from'] except (KeyError, TypeError): msg = ('profile has undefined url, auth_key or auth_context') log.debug(msg) return ret region = profile_data.get('region', 'us-east-1') token_duration = profile_data.get('token_duration', 60) retries = profile_data.get('retries', 5) token_cache_file = profile_data.get('token_cache_file') backoff = profile_data.get('backoff', 1) client = confidant.client.ConfidantClient( url, auth_key, auth_context, token_lifetime=token_duration, token_version=token_version, token_cache_file=token_cache_file, region=region, retries=retries, backoff=backoff ) try: data = client.get_service( role, decrypt_blind=True ) except confidant.client.TokenCreationError: return ret if not data['result']: return ret ret = confidant.formatter.combined_credential_pair_format(data) ret['credentials_result'] = True return ret
Read pillar data from Confidant via its API.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/confidant.py#L70-L123
null
# -*- coding: utf-8 -*- ''' An external pillar module for getting credentials from confidant. Configuring the Confidant module ================================ The module can be configured via ext_pillar in the minion config: .. code-block:: yaml ext_pillar: - confidant: profile: # The URL of the confidant web service url: 'https://confidant-production.example.com' # The context to use for KMS authentication auth_context: from: example-production-iad to: confidant-production-iad user_type: service # The KMS master key to use for authentication auth_key: "alias/authnz" # Cache file for KMS auth token token_cache_file: /run/confidant/confidant_token # The duration of the validity of a token, in minutes token_duration: 60 # key, keyid and region can be defined in the profile, but it's # generally best to use IAM roles or environment variables for AWS # auth. keyid: 98nh9h9h908h09kjjk key: jhf908gyeghehe0he0g8h9u0j0n0n09hj09h0 region: us-east-1 :depends: confidant-common, confidant-client Module Documentation ==================== ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import logging import copy # Import third party libs try: import confidant.client import confidant.formatter HAS_LIBS = True except ImportError: HAS_LIBS = False # Set up logging log = logging.getLogger(__name__) __virtualname__ = 'confidant' def __virtual__(): ''' Only return if requests and boto are installed. ''' if HAS_LIBS: return __virtualname__ else: return False
saltstack/salt
salt/log/setup.py
setup_temp_logger
python
def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True
Setup the temporary console logger
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L457-L508
[ "def is_temp_logging_configured():\n return __TEMP_LOGGING_CONFIGURED\n" ]
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
setup_console_logger
python
def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler
Setup the console logger
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L511-L559
[ "def setLogRecordFactory(factory):\n '''\n Set the factory to be used when instantiating a log record.\n\n :param factory: A callable which will be called to instantiate\n a log record.\n '''\n global _LOG_RECORD_FACTORY\n _LOG_RECORD_FACTORY = factory\n", "def is_console_configured():\n return __CONSOLE_CONFIGURED\n", "def __remove_temp_logging_handler():\n '''\n This function will run once logging has been configured. It just removes\n the temporary stream Handler from the logging handlers.\n '''\n if is_logging_configured():\n # In this case, the temporary logging handler has been removed, return!\n return\n\n # This should already be done, but...\n __remove_null_logging_handler()\n\n root_logger = logging.getLogger()\n global LOGGING_TEMP_HANDLER\n\n for handler in root_logger.handlers:\n if handler is LOGGING_TEMP_HANDLER:\n root_logger.removeHandler(LOGGING_TEMP_HANDLER)\n # Redefine the null handler to None so it can be garbage collected\n LOGGING_TEMP_HANDLER = None\n break\n\n if sys.version_info >= (2, 7):\n # Python versions >= 2.7 allow warnings to be redirected to the logging\n # system now that it's configured. Let's enable it.\n logging.captureWarnings(True)\n" ]
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
setup_logfile_logger
python
def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler
Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L562-L739
[ "def is_logfile_configured():\n return __LOGFILE_CONFIGURED\n", "def shutdown_multiprocessing_logging_listener(daemonizing=False):\n global __MP_LOGGING_QUEUE\n global __MP_LOGGING_QUEUE_PROCESS\n global __MP_LOGGING_LISTENER_CONFIGURED\n\n if daemonizing is False and __MP_IN_MAINPROCESS is True:\n # We're in the MainProcess and we're not daemonizing, return!\n # No multiprocessing logging listener shutdown shall happen\n return\n\n if not daemonizing:\n # Need to remove the queue handler so that it doesn't try to send\n # data over a queue that was shut down on the listener end.\n shutdown_multiprocessing_logging()\n\n if __MP_LOGGING_QUEUE_PROCESS is None:\n return\n\n if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid():\n # We're not in the MainProcess, return! No logging listener setup shall happen\n return\n\n if __MP_LOGGING_QUEUE_PROCESS.is_alive():\n logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener')\n try:\n # Sent None sentinel to stop the logging processing queue\n __MP_LOGGING_QUEUE.put(None)\n # Let's join the multiprocessing logging handle thread\n time.sleep(0.5)\n logging.getLogger(__name__).debug('closing multiprocessing queue')\n __MP_LOGGING_QUEUE.close()\n logging.getLogger(__name__).debug('joining multiprocessing queue thread')\n __MP_LOGGING_QUEUE.join_thread()\n __MP_LOGGING_QUEUE = None\n __MP_LOGGING_QUEUE_PROCESS.join(1)\n __MP_LOGGING_QUEUE = None\n except IOError:\n # We were unable to deliver the sentinel to the queue\n # carry on...\n pass\n if __MP_LOGGING_QUEUE_PROCESS.is_alive():\n # Process is still alive!?\n __MP_LOGGING_QUEUE_PROCESS.terminate()\n __MP_LOGGING_QUEUE_PROCESS = None\n __MP_LOGGING_LISTENER_CONFIGURED = False\n logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener')\n", "def __remove_temp_logging_handler():\n '''\n This function will run once logging has been configured. It just removes\n the temporary stream Handler from the logging handlers.\n '''\n if is_logging_configured():\n # In this case, the temporary logging handler has been removed, return!\n return\n\n # This should already be done, but...\n __remove_null_logging_handler()\n\n root_logger = logging.getLogger()\n global LOGGING_TEMP_HANDLER\n\n for handler in root_logger.handlers:\n if handler is LOGGING_TEMP_HANDLER:\n root_logger.removeHandler(LOGGING_TEMP_HANDLER)\n # Redefine the null handler to None so it can be garbage collected\n LOGGING_TEMP_HANDLER = None\n break\n\n if sys.version_info >= (2, 7):\n # Python versions >= 2.7 allow warnings to be redirected to the logging\n # system now that it's configured. Let's enable it.\n logging.captureWarnings(True)\n" ]
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
setup_extended_logging
python
def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True
Setup any additional logging handlers, internal or external
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L742-L824
[ "def is_extended_logging_configured():\n return __EXTERNAL_LOGGERS_CONFIGURED\n" ]
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
set_multiprocessing_logging_level_by_opts
python
def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels)
This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L854-L870
[ "def itervalues(d, **kw):\n return d.itervalues(**kw)\n" ]
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
setup_multiprocessing_logging
python
def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock()
This code should be called from within a running multiprocessing process instance.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L899-L950
null
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
set_logger_level
python
def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) )
Tweak a specific logger's logging level
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1060-L1066
null
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
patch_python_logging_handlers
python
def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler
Patch the python logging handlers with out mixed-in classes
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1069-L1079
null
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
__remove_null_logging_handler
python
def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break
This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1132-L1149
null
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler
saltstack/salt
salt/log/setup.py
__remove_queue_logging_handler
python
def __remove_queue_logging_handler(): ''' This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers. ''' global LOGGING_STORE_HANDLER if LOGGING_STORE_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_STORE_HANDLER: root_logger.removeHandler(LOGGING_STORE_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_STORE_HANDLER = None break
This function will run once the additional loggers have been synchronized. It just removes the QueueLoggingHandler from the logging handlers.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1152-L1169
null
# -*- coding: utf-8 -*- ''' :codeauthor: Pedro Algarvio (pedro@algarvio.me) salt.log.setup ~~~~~~~~~~~~~~ This is where Salt's logging gets set up. This module should be imported as soon as possible, preferably the first module salt or any salt depending library imports so any new logging logger instance uses our ``salt.log.setup.SaltLoggingClass``. ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import os import re import sys import time import types import socket import logging import logging.handlers import traceback import multiprocessing # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module # Let's define these custom logging levels before importing the salt.log.mixins # since they will be used there PROFILE = logging.PROFILE = 15 TRACE = logging.TRACE = 5 GARBAGE = logging.GARBAGE = 1 QUIET = logging.QUIET = 1000 # Import salt libs from salt.textformat import TextFormat from salt.log.handlers import (TemporaryLoggingHandler, StreamHandler, SysLogHandler, FileHandler, WatchedFileHandler, RotatingFileHandler, QueueHandler) from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn from salt.utils.ctx import RequestContext LOG_LEVELS = { 'all': logging.NOTSET, 'debug': logging.DEBUG, 'error': logging.ERROR, 'critical': logging.CRITICAL, 'garbage': GARBAGE, 'info': logging.INFO, 'profile': PROFILE, 'quiet': QUIET, 'trace': TRACE, 'warning': logging.WARNING, } LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items()) LOG_COLORS = { 'levels': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('bold', 'red'), 'WARNING': TextFormat('bold', 'yellow'), 'INFO': TextFormat('bold', 'green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('bold', 'cyan'), 'TRACE': TextFormat('bold', 'magenta'), 'GARBAGE': TextFormat('bold', 'blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'msgs': { 'QUIET': TextFormat('reset'), 'CRITICAL': TextFormat('bold', 'red'), 'ERROR': TextFormat('red'), 'WARNING': TextFormat('yellow'), 'INFO': TextFormat('green'), 'PROFILE': TextFormat('bold', 'cyan'), 'DEBUG': TextFormat('cyan'), 'TRACE': TextFormat('magenta'), 'GARBAGE': TextFormat('blue'), 'NOTSET': TextFormat('reset'), 'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr() 'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr() }, 'name': TextFormat('bold', 'green'), 'process': TextFormat('bold', 'blue'), } # Make a list of log level names sorted by log level SORTED_LEVEL_NAMES = [ l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1]) ] # Store an instance of the current logging logger class LOGGING_LOGGER_CLASS = logging.getLoggerClass() MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)') __CONSOLE_CONFIGURED = False __LOGGING_CONSOLE_HANDLER = None __LOGFILE_CONFIGURED = False __LOGGING_LOGFILE_HANDLER = None __TEMP_LOGGING_CONFIGURED = False __EXTERNAL_LOGGERS_CONFIGURED = False __MP_LOGGING_LISTENER_CONFIGURED = False __MP_LOGGING_CONFIGURED = False __MP_LOGGING_QUEUE = None __MP_LOGGING_LEVEL = GARBAGE __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_QUEUE_HANDLER = None __MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess' __MP_MAINPROCESS_ID = None class __NullLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' class __StoreLoggingHandler(TemporaryLoggingHandler): ''' This class exists just to better identify which temporary logging handler is being used for what. ''' def is_console_configured(): return __CONSOLE_CONFIGURED def is_logfile_configured(): return __LOGFILE_CONFIGURED def is_logging_configured(): return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED def is_temp_logging_configured(): return __TEMP_LOGGING_CONFIGURED def is_mp_logging_listener_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_mp_logging_configured(): return __MP_LOGGING_LISTENER_CONFIGURED def is_extended_logging_configured(): return __EXTERNAL_LOGGERS_CONFIGURED # Store a reference to the temporary queue logging handler LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING) # Store a reference to the temporary console logger LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr) # Store a reference to the "storing" logging handler LOGGING_STORE_HANDLER = __StoreLoggingHandler() class SaltLogQueueHandler(QueueHandler): pass class SaltLogRecord(logging.LogRecord): def __init__(self, *args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) # pylint: disable=E1321 self.bracketname = '[%-17s]' % self.name self.bracketlevel = '[%-8s]' % self.levelname self.bracketprocess = '[%5s]' % self.process # pylint: enable=E1321 class SaltColorLogRecord(SaltLogRecord): def __init__(self, *args, **kwargs): SaltLogRecord.__init__(self, *args, **kwargs) reset = TextFormat('reset') clevel = LOG_COLORS['levels'].get(self.levelname, reset) cmsg = LOG_COLORS['msgs'].get(self.levelname, reset) # pylint: disable=E1321 self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'], self.name, reset) self.colorlevel = '%s[%-8s]%s' % (clevel, self.levelname, reset) self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'], self.process, reset) self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset) # pylint: enable=E1321 _LOG_RECORD_FACTORY = SaltLogRecord def setLogRecordFactory(factory): ''' Set the factory to be used when instantiating a log record. :param factory: A callable which will be called to instantiate a log record. ''' global _LOG_RECORD_FACTORY _LOG_RECORD_FACTORY = factory def getLogRecordFactory(): ''' Return the factory to be used when instantiating a log record. ''' return _LOG_RECORD_FACTORY setLogRecordFactory(SaltLogRecord) class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)): def __new__(cls, *args): # pylint: disable=W0613,E0012 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be executed when the class is instantiated, i.e.: logging.getLogger(__name__) ''' instance = super(SaltLoggingClass, cls).__new__(cls) try: max_logger_length = len(max( list(logging.Logger.manager.loggerDict), key=len )) for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER, LOGGING_TEMP_HANDLER): continue formatter = handler.formatter if not formatter: continue if not handler.lock: handler.createLock() handler.acquire() fmt = formatter._fmt.replace('%', '%%') match = MODNAME_PATTERN.search(fmt) if not match: # Not matched. Release handler and return. handler.release() return instance if 'digits' not in match.groupdict(): # No digits group. Release handler and return. handler.release() return instance digits = match.group('digits') if not digits or not (digits and digits.isdigit()): # No valid digits. Release handler and return. handler.release() return instance if int(digits) < max_logger_length: # Formatter digits value is lower than current max, update. fmt = fmt.replace(match.group('name'), '%%(name)-%ds') formatter = logging.Formatter( fmt % max_logger_length, datefmt=formatter.datefmt ) handler.setFormatter(formatter) handler.release() except ValueError: # There are no registered loggers yet pass return instance def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ exc_info_on_loglevel=None): # If both exc_info and exc_info_on_loglevel are both passed, let's fail if extra is None: extra = {} current_jid = RequestContext.current.get('data', {}).get('jid', None) log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None) if current_jid is not None: extra['jid'] = current_jid if log_fmt_jid is not None: extra['log_fmt_jid'] = log_fmt_jid if exc_info and exc_info_on_loglevel: raise RuntimeError( 'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is ' 'permitted' ) if exc_info_on_loglevel is not None: if isinstance(exc_info_on_loglevel, six.string_types): exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel, logging.ERROR) elif not isinstance(exc_info_on_loglevel, int): raise RuntimeError( 'The value of \'exc_info_on_loglevel\' needs to be a ' 'logging level or a logging level name, not \'{0}\'' .format(exc_info_on_loglevel) ) if extra is None: extra = {'exc_info_on_loglevel': exc_info_on_loglevel} else: extra['exc_info_on_loglevel'] = exc_info_on_loglevel LOGGING_LOGGER_CLASS._log( self, level, msg, args, exc_info=exc_info, extra=extra ) # pylint: disable=C0103 # pylint: disable=W0221 def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') jid = extra.pop('jid', '') if jid: log_fmt_jid = extra.pop('log_fmt_jid') jid = log_fmt_jid % {'jid': jid} if not extra: # If nothing else is in extra, make it None extra = None # Let's try to make every logging message unicode salt_system_encoding = __salt_system_encoding__ if salt_system_encoding == 'ascii': # Encoding detection most likely failed, let's use the utf-8 # value which we defaulted before __salt_system_encoding__ was # implemented salt_system_encoding = 'utf-8' if isinstance(msg, six.string_types) \ and not isinstance(msg, six.text_type): try: _msg = msg.decode(salt_system_encoding, 'replace') except UnicodeDecodeError: _msg = msg.decode(salt_system_encoding, 'ignore') else: _msg = msg _args = [] for item in args: if isinstance(item, six.string_types) \ and not isinstance(item, six.text_type): try: _args.append(item.decode(salt_system_encoding, 'replace')) except UnicodeDecodeError: _args.append(item.decode(salt_system_encoding, 'ignore')) else: _args.append(item) _args = tuple(_args) if six.PY3: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func, sinfo) else: logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args, exc_info, func) if extra is not None: for key in extra: if (key in ['message', 'asctime']) or (key in logrecord.__dict__): raise KeyError( 'Attempt to overwrite \'{0}\' in LogRecord'.format(key) ) logrecord.__dict__[key] = extra[key] if exc_info_on_loglevel is not None: # Let's add some custom attributes to the LogRecord class in order # to include the exc_info on a per handler basis. This will allow # showing tracebacks on logfiles but not on console if the logfile # handler is enabled for the log level "exc_info_on_loglevel" and # console handler is not. logrecord.exc_info_on_loglevel_instance = sys.exc_info() logrecord.exc_info_on_loglevel_formatted = None logrecord.exc_info_on_loglevel = exc_info_on_loglevel logrecord.jid = jid return logrecord # pylint: enable=C0103 # Override the python's logging logger class as soon as this module is imported if logging.getLoggerClass() is not SaltLoggingClass: logging.setLoggerClass(SaltLoggingClass) logging.addLevelName(QUIET, 'QUIET') logging.addLevelName(PROFILE, 'PROFILE') logging.addLevelName(TRACE, 'TRACE') logging.addLevelName(GARBAGE, 'GARBAGE') if not logging.root.handlers: # No configuration to the logging system has been done so far. # Set the root logger at the lowest level possible logging.root.setLevel(GARBAGE) # Add a Null logging handler until logging is configured(will be # removed at a later stage) so we stop getting: # No handlers could be found for logger 'foo' logging.root.addHandler(LOGGING_NULL_HANDLER) # Add the queue logging handler so we can later sync all message records # with the additional logging handlers logging.root.addHandler(LOGGING_STORE_HANDLER) def getLogger(name): # pylint: disable=C0103 ''' This function is just a helper, an alias to: logging.getLogger(name) Although you might find it useful, there's no reason why you should not be using the aliased method. ''' return logging.getLogger(name) def setup_temp_logger(log_level='error'): ''' Setup the temporary console logger ''' if is_temp_logging_configured(): logging.getLogger(__name__).warning( 'Temporary logging is already configured' ) return if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) handler = None for handler in logging.root.handlers: if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER): continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = LOGGING_TEMP_HANDLER handler.setLevel(level) # Set the default temporary console formatter config formatter = logging.Formatter( '[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S' ) handler.setFormatter(formatter) logging.root.addHandler(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_NULL_HANDLER is not None: LOGGING_NULL_HANDLER.sync_with_handlers([handler]) else: logging.getLogger(__name__).debug( 'LOGGING_NULL_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary null logging handler __remove_null_logging_handler() global __TEMP_LOGGING_CONFIGURED __TEMP_LOGGING_CONFIGURED = True def setup_console_logger(log_level='error', log_format=None, date_format=None): ''' Setup the console logger ''' if is_console_configured(): logging.getLogger(__name__).warning('Console logging already configured') return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) setLogRecordFactory(SaltColorLogRecord) handler = None for handler in logging.root.handlers: if handler is LOGGING_STORE_HANDLER: continue if not hasattr(handler, 'stream'): # Not a stream handler, continue continue if handler.stream is sys.stderr: # There's already a logging handler outputting to sys.stderr break else: handler = StreamHandler(sys.stderr) handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '[%(levelname)-8s] %(message)s' if not date_format: date_format = '%H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) logging.root.addHandler(handler) global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER __CONSOLE_CONFIGURED = True __LOGGING_CONSOLE_HANDLER = handler def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None, max_bytes=0, backup_count=0): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:5145/LOG_KERN udp://localhost file:///dev/log file:///dev/log/LOG_SYSLOG file:///dev/log/LOG_DAEMON The above examples are self explanatory, but: <file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility> If you're thinking on doing remote logging you might also be thinking that you could point salt's logging to the remote syslog. **Please Don't!** An issue has been reported when doing this over TCP when the logged lines get concatenated. See #3061. The preferred way to do remote logging is setup a local syslog, point salt's logging to the local syslog(unix socket is much faster) and then have the local syslog forward the log messages to the remote syslog. ''' if is_logfile_configured(): logging.getLogger(__name__).warning('Logfile logging already configured') return if log_path is None: logging.getLogger(__name__).warning( 'log_path setting is set to `None`. Nothing else to do' ) return # Remove the temporary logging handler __remove_temp_logging_handler() if log_level is None: log_level = 'warning' level = LOG_LEVELS.get(log_level.lower(), logging.ERROR) parsed_log_path = urlparse(log_path) root_logger = logging.getLogger() if parsed_log_path.scheme in ('tcp', 'udp', 'file'): syslog_opts = { 'facility': SysLogHandler.LOG_USER, 'socktype': socket.SOCK_DGRAM } if parsed_log_path.scheme == 'file' and parsed_log_path.path: facility_name = parsed_log_path.path.split(os.sep)[-1].upper() if not facility_name.startswith('LOG_'): # The user is not specifying a syslog facility facility_name = 'LOG_USER' # Syslog default syslog_opts['address'] = parsed_log_path.path else: # The user has set a syslog facility, let's update the path to # the logging socket syslog_opts['address'] = os.sep.join( parsed_log_path.path.split(os.sep)[:-1] ) elif parsed_log_path.path: # In case of udp or tcp with a facility specified facility_name = parsed_log_path.path.lstrip(os.sep).upper() if not facility_name.startswith('LOG_'): # Logging facilities start with LOG_ if this is not the case # fail right now! raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) else: # This is the case of udp or tcp without a facility specified facility_name = 'LOG_USER' # Syslog default facility = getattr( SysLogHandler, facility_name, None ) if facility is None: # This python syslog version does not know about the user provided # facility name raise RuntimeError( 'The syslog facility \'{0}\' is not known'.format( facility_name ) ) syslog_opts['facility'] = facility if parsed_log_path.scheme == 'tcp': # tcp syslog support was only added on python versions >= 2.7 if sys.version_info < (2, 7): raise RuntimeError( 'Python versions lower than 2.7 do not support logging ' 'to syslog using tcp sockets' ) syslog_opts['socktype'] = socket.SOCK_STREAM if parsed_log_path.scheme in ('tcp', 'udp'): syslog_opts['address'] = ( parsed_log_path.hostname, parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT ) if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file': # There's not socktype support on python versions lower than 2.7 syslog_opts.pop('socktype', None) try: # Et voilá! Finally our syslog handler instance handler = SysLogHandler(**syslog_opts) except socket.error as err: logging.getLogger(__name__).error( 'Failed to setup the Syslog logging handler: %s', err ) shutdown_multiprocessing_logging_listener() sys.exit(2) else: # make sure, the logging directory exists and attempt to create it if necessary log_dir = os.path.dirname(log_path) if not os.path.exists(log_dir): logging.getLogger(__name__).info( 'Log directory not found, trying to create it: %s', log_dir ) try: os.makedirs(log_dir, mode=0o700) except OSError as ose: logging.getLogger(__name__).warning( 'Failed to create directory for log file: %s (%s)', log_dir, ose ) return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a # user is not using plain ASCII, their system should be ready to # handle UTF-8. if max_bytes > 0: handler = RotatingFileHandler(log_path, mode='a', maxBytes=max_bytes, backupCount=backup_count, encoding='utf-8', delay=0) else: handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0) except (IOError, OSError): logging.getLogger(__name__).warning( 'Failed to open log file, do you have permission to write to %s?', log_path ) # Do not proceed with any more configuration since it will fail, we # have the console logging already setup and the user should see # the error. return handler.setLevel(level) # Set the default console formatter config if not log_format: log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s' if not date_format: date_format = '%Y-%m-%d %H:%M:%S' formatter = logging.Formatter(log_format, datefmt=date_format) handler.setFormatter(formatter) root_logger.addHandler(handler) global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER __LOGFILE_CONFIGURED = True __LOGGING_LOGFILE_HANDLER = handler def setup_extended_logging(opts): ''' Setup any additional logging handlers, internal or external ''' if is_extended_logging_configured() is True: # Don't re-configure external loggers return # Explicit late import of salt's loader import salt.loader # Let's keep a reference to the current logging handlers initial_handlers = logging.root.handlers[:] # Load any additional logging handlers providers = salt.loader.log_handlers(opts) # Let's keep track of the new logging handlers so we can sync the stored # log records with them additional_handlers = [] for name, get_handlers_func in six.iteritems(providers): logging.getLogger(__name__).info('Processing `log_handlers.%s`', name) # Keep a reference to the logging handlers count before getting the # possible additional ones. initial_handlers_count = len(logging.root.handlers) handlers = get_handlers_func() if isinstance(handlers, types.GeneratorType): handlers = list(handlers) elif handlers is False or handlers == [False]: # A false return value means not configuring any logging handler on # purpose logging.getLogger(__name__).info( 'The `log_handlers.%s.setup_handlers()` function returned ' '`False` which means no logging handler was configured on ' 'purpose. Continuing...', name ) continue else: # Make sure we have an iterable handlers = [handlers] for handler in handlers: if not handler and \ len(logging.root.handlers) == initial_handlers_count: logging.getLogger(__name__).info( 'The `log_handlers.%s`, did not return any handlers ' 'and the global handlers count did not increase. This ' 'could be a sign of `log_handlers.%s` not working as ' 'supposed', name, name ) continue logging.getLogger(__name__).debug( 'Adding the \'%s\' provided logging handler: \'%s\'', name, handler ) additional_handlers.append(handler) logging.root.addHandler(handler) for handler in logging.root.handlers: if handler in initial_handlers: continue additional_handlers.append(handler) # Sync the null logging handler messages with the temporary handler if LOGGING_STORE_HANDLER is not None: LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers) else: logging.getLogger(__name__).debug( 'LOGGING_STORE_HANDLER is already None, can\'t sync messages ' 'with it' ) # Remove the temporary queue logging handler __remove_queue_logging_handler() # Remove the temporary null logging handler (if it exists) __remove_null_logging_handler() global __EXTERNAL_LOGGERS_CONFIGURED __EXTERNAL_LOGGERS_CONFIGURED = True def get_multiprocessing_logging_queue(): global __MP_LOGGING_QUEUE if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No Queue shall be instantiated return __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is None: __MP_LOGGING_QUEUE = multiprocessing.Queue() return __MP_LOGGING_QUEUE def set_multiprocessing_logging_queue(queue): global __MP_LOGGING_QUEUE if __MP_LOGGING_QUEUE is not queue: __MP_LOGGING_QUEUE = queue def get_multiprocessing_logging_level(): return __MP_LOGGING_LEVEL def set_multiprocessing_logging_level(log_level): global __MP_LOGGING_LEVEL __MP_LOGGING_LEVEL = log_level def set_multiprocessing_logging_level_by_opts(opts): ''' This will set the multiprocessing logging level to the lowest logging level of all the types of logging that are configured. ''' global __MP_LOGGING_LEVEL log_levels = [ LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR), LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR) ] for level in six.itervalues(opts.get('log_granular_levels', {})): log_levels.append( LOG_LEVELS.get(level.lower(), logging.ERROR) ) __MP_LOGGING_LEVEL = min(log_levels) def setup_multiprocessing_logging_listener(opts, queue=None): global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED global __MP_MAINPROCESS_ID if __MP_IN_MAINPROCESS is False: # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_LISTENER_CONFIGURED is True: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, args=(opts, queue or get_multiprocessing_logging_queue(),) ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() __MP_LOGGING_LISTENER_CONFIGURED = True def setup_multiprocessing_logging(queue=None): ''' This code should be called from within a running multiprocessing process instance. ''' from salt.utils.platform import is_windows global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if __MP_IN_MAINPROCESS is True and not is_windows(): # We're in the MainProcess, return! No multiprocessing logging setup shall happen # Windows is the exception where we want to set up multiprocessing # logging in the MainProcess. return try: logging._acquireLock() # pylint: disable=protected-access if __MP_LOGGING_CONFIGURED is True: return # Let's set it to true as fast as possible __MP_LOGGING_CONFIGURED = True if __MP_LOGGING_QUEUE_HANDLER is not None: return # The temp null and temp queue logging handlers will store messages. # Since noone will process them, memory usage will grow. If they # exist, remove them. __remove_null_logging_handler() __remove_queue_logging_handler() # Let's add a queue handler to the logging root handlers __MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue()) logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER) # Set the logging root level to the lowest needed level to get all # desired messages. log_level = get_multiprocessing_logging_level() logging.root.setLevel(log_level) logging.getLogger(__name__).debug( 'Multiprocessing queue logging configured for the process running ' 'under PID: %s at log level %s', os.getpid(), log_level ) # The above logging call will create, in some situations, a futex wait # lock condition, probably due to the multiprocessing Queue's internal # lock and semaphore mechanisms. # A small sleep will allow us not to hit that futex wait lock condition. time.sleep(0.0001) finally: logging._releaseLock() # pylint: disable=protected-access def shutdown_console_logging(): global __CONSOLE_CONFIGURED global __LOGGING_CONSOLE_HANDLER if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER) __LOGGING_CONSOLE_HANDLER = None __CONSOLE_CONFIGURED = False finally: logging._releaseLock() def shutdown_logfile_logging(): global __LOGFILE_CONFIGURED global __LOGGING_LOGFILE_HANDLER if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER: return try: logging._acquireLock() logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER) __LOGGING_LOGFILE_HANDLER = None __LOGFILE_CONFIGURED = False finally: logging._releaseLock() def shutdown_temp_logging(): __remove_temp_logging_handler() def shutdown_multiprocessing_logging(): global __MP_LOGGING_CONFIGURED global __MP_LOGGING_QUEUE_HANDLER if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER: return try: logging._acquireLock() # Let's remove the queue handler from the logging root handlers logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER) __MP_LOGGING_QUEUE_HANDLER = None __MP_LOGGING_CONFIGURED = False if not logging.root.handlers: # Ensure we have at least one logging root handler so # something can handle logging messages. This case should # only occur on Windows since on Windows we log to console # and file through the Multiprocessing Logging Listener. setup_console_logger() finally: logging._releaseLock() def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # No multiprocessing logging listener shutdown shall happen return if not daemonizing: # Need to remove the queue handler so that it doesn't try to send # data over a queue that was shut down on the listener end. shutdown_multiprocessing_logging() if __MP_LOGGING_QUEUE_PROCESS is None: return if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid(): # We're not in the MainProcess, return! No logging listener setup shall happen return if __MP_LOGGING_QUEUE_PROCESS.is_alive(): logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener') try: # Sent None sentinel to stop the logging processing queue __MP_LOGGING_QUEUE.put(None) # Let's join the multiprocessing logging handle thread time.sleep(0.5) logging.getLogger(__name__).debug('closing multiprocessing queue') __MP_LOGGING_QUEUE.close() logging.getLogger(__name__).debug('joining multiprocessing queue thread') __MP_LOGGING_QUEUE.join_thread() __MP_LOGGING_QUEUE = None __MP_LOGGING_QUEUE_PROCESS.join(1) __MP_LOGGING_QUEUE = None except IOError: # We were unable to deliver the sentinel to the queue # carry on... pass if __MP_LOGGING_QUEUE_PROCESS.is_alive(): # Process is still alive!? __MP_LOGGING_QUEUE_PROCESS.terminate() __MP_LOGGING_QUEUE_PROCESS = None __MP_LOGGING_LISTENER_CONFIGURED = False logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener') def set_logger_level(logger_name, log_level='error'): ''' Tweak a specific logger's logging level ''' logging.getLogger(logger_name).setLevel( LOG_LEVELS.get(log_level.lower(), logging.ERROR) ) def patch_python_logging_handlers(): ''' Patch the python logging handlers with out mixed-in classes ''' logging.StreamHandler = StreamHandler logging.FileHandler = FileHandler logging.handlers.SysLogHandler = SysLogHandler logging.handlers.WatchedFileHandler = WatchedFileHandler logging.handlers.RotatingFileHandler = RotatingFileHandler if sys.version_info >= (3, 2): logging.handlers.QueueHandler = QueueHandler def __process_multiprocessing_logging_queue(opts, queue): # Avoid circular import import salt.utils.process salt.utils.process.appendproctitle('MultiprocessingLoggingQueue') # Assign UID/GID of user to proc if set from salt.utils.verify import check_user user = opts.get('user') if user: check_user(user) from salt.utils.platform import is_windows if is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup all of our logging # inside this process. setup_temp_logger() setup_console_logger( log_level=opts.get('log_level'), log_format=opts.get('log_fmt_console'), date_format=opts.get('log_datefmt_console') ) setup_logfile_logger( opts.get('log_file'), log_level=opts.get('log_level_logfile'), log_format=opts.get('log_fmt_logfile'), date_format=opts.get('log_datefmt_logfile'), max_bytes=opts.get('log_rotate_max_bytes', 0), backup_count=opts.get('log_rotate_backup_count', 0) ) setup_extended_logging(opts) while True: try: record = queue.get() if record is None: # A sentinel to stop processing the queue break # Just log everything, filtering will happen on the main process # logging handlers logger = logging.getLogger(record.name) logger.handle(record) except (EOFError, KeyboardInterrupt, SystemExit): break except Exception as exc: # pylint: disable=broad-except logging.getLogger(__name__).warning( 'An exception occurred in the multiprocessing logging ' 'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG ) def __remove_null_logging_handler(): ''' This function will run once the temporary logging has been configured. It just removes the NullHandler from the logging handlers. ''' global LOGGING_NULL_HANDLER if LOGGING_NULL_HANDLER is None: # Already removed return root_logger = logging.getLogger() for handler in root_logger.handlers: if handler is LOGGING_NULL_HANDLER: root_logger.removeHandler(LOGGING_NULL_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_NULL_HANDLER = None break def __remove_temp_logging_handler(): ''' This function will run once logging has been configured. It just removes the temporary stream Handler from the logging handlers. ''' if is_logging_configured(): # In this case, the temporary logging handler has been removed, return! return # This should already be done, but... __remove_null_logging_handler() root_logger = logging.getLogger() global LOGGING_TEMP_HANDLER for handler in root_logger.handlers: if handler is LOGGING_TEMP_HANDLER: root_logger.removeHandler(LOGGING_TEMP_HANDLER) # Redefine the null handler to None so it can be garbage collected LOGGING_TEMP_HANDLER = None break if sys.version_info >= (2, 7): # Python versions >= 2.7 allow warnings to be redirected to the logging # system now that it's configured. Let's enable it. logging.captureWarnings(True) def __global_logging_exception_handler(exc_type, exc_value, exc_traceback): ''' This function will log all un-handled python exceptions. ''' if exc_type.__name__ == "KeyboardInterrupt": # Do not log the exception or display the traceback on Keyboard Interrupt # Stop the logging queue listener thread if is_mp_logging_listener_configured(): shutdown_multiprocessing_logging_listener() else: # Log the exception logging.getLogger(__name__).error( 'An un-handled exception was caught by salt\'s global exception ' 'handler:\n%s: %s\n%s', exc_type.__name__, exc_value, ''.join(traceback.format_exception( exc_type, exc_value, exc_traceback )).strip() ) # Call the original sys.excepthook sys.__excepthook__(exc_type, exc_value, exc_traceback) # Set our own exception handler as the one to use sys.excepthook = __global_logging_exception_handler