repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/consul.py | agent_members | 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 | 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 | [
"def",
"agent_members",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if... | 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 | [
"Returns",
"the",
"members",
"as",
"seen",
"by",
"the",
"local",
"serf",
"agent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L471-L504 | train |
saltstack/salt | salt/modules/consul.py | agent_self | 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 | 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 | [
"def",
"agent_self",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"not",
"consul_url",
":",
... | 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 | [
"Returns",
"the",
"local",
"node",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L507-L537 | train |
saltstack/salt | salt/modules/consul.py | agent_maintenance | 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 | 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 | [
"def",
"agent_maintenance",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
... | 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' | [
"Manages",
"node",
"maintenance",
"mode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L540-L594 | train |
saltstack/salt | salt/modules/consul.py | agent_leave | 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 | 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 | [
"def",
"agent_leave",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"node",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if"... | 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' | [
"Used",
"to",
"instruct",
"the",
"agent",
"to",
"force",
"a",
"node",
"into",
"the",
"left",
"state",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L644-L684 | train |
saltstack/salt | salt/modules/consul.py | agent_check_register | 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 | 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 | [
"def",
"agent_check_register",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if"... | 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' | [
"The",
"register",
"endpoint",
"is",
"used",
"to",
"add",
"a",
"new",
"check",
"to",
"the",
"local",
"agent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L687-L772 | train |
saltstack/salt | salt/modules/consul.py | agent_check_deregister | 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 | 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 | [
"def",
"agent_check_deregister",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"checkid",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"not",
"consul_url"... | 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' | [
"The",
"agent",
"will",
"take",
"care",
"of",
"deregistering",
"the",
"check",
"from",
"the",
"Catalog",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L775-L813 | train |
saltstack/salt | salt/modules/consul.py | agent_check_warn | 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 | 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 | [
"def",
"agent_check_warn",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"checkid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"... | 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.' | [
"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",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L865-L911 | train |
saltstack/salt | salt/modules/consul.py | agent_service_register | 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 | 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 | [
"def",
"agent_service_register",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"i... | 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" | [
"The",
"used",
"to",
"add",
"a",
"new",
"service",
"with",
"an",
"optional",
"health",
"check",
"to",
"the",
"local",
"agent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L963-L1074 | train |
saltstack/salt | salt/modules/consul.py | agent_service_deregister | 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 | 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 | [
"def",
"agent_service_deregister",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"serviceid",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
"... | 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' | [
"Used",
"to",
"remove",
"a",
"service",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1077-L1117 | train |
saltstack/salt | salt/modules/consul.py | agent_service_maintenance | 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 | 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 | [
"def",
"agent_service_maintenance",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"serviceid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consu... | 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' | [
"Used",
"to",
"place",
"a",
"service",
"into",
"maintenance",
"mode",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1120-L1175 | train |
saltstack/salt | salt/modules/consul.py | session_create | 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 | 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 | [
"def",
"session_create",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"not",
"consul_url",
":",
"... | 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' | [
"Used",
"to",
"create",
"a",
"session",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1178-L1266 | train |
saltstack/salt | salt/modules/consul.py | session_list | 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 | 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 | [
"def",
"session_list",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"return_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"... | 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 | [
"Used",
"to",
"list",
"sessions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1269-L1313 | train |
saltstack/salt | salt/modules/consul.py | session_destroy | 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 | 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 | [
"def",
"session_destroy",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if... | 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' | [
"Destroy",
"session"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1316-L1361 | train |
saltstack/salt | salt/modules/consul.py | session_info | 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 | 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 | [
"def",
"session_info",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
... | 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' | [
"Information",
"about",
"a",
"session"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1364-L1403 | train |
saltstack/salt | salt/modules/consul.py | catalog_register | 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 | 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 | [
"def",
"catalog_register",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"data",
"[",
"'NodeMeta'",
"]",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"... | 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' | [
"Registers",
"a",
"new",
"node",
"service",
"or",
"check"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1406-L1564 | train |
saltstack/salt | salt/modules/consul.py | catalog_datacenters | 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 | 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 | [
"def",
"catalog_datacenters",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"not",
"consul_url",
":",
"log",
".",
"error",
"(... | 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 | [
"Return",
"list",
"of",
"available",
"datacenters",
"from",
"catalog",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1629-L1656 | train |
saltstack/salt | salt/modules/consul.py | catalog_nodes | 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 | 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 | [
"def",
"catalog_nodes",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if... | 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 | [
"Return",
"list",
"of",
"available",
"nodes",
"from",
"catalog",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1659-L1693 | train |
saltstack/salt | salt/modules/consul.py | health_node | 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 | 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 | [
"def",
"health_node",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"node",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_... | 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' | [
"Health",
"information",
"about",
"the",
"registered",
"node",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1818-L1856 | train |
saltstack/salt | salt/modules/consul.py | health_checks | 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 | 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 | [
"def",
"health_checks",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"service",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",... | 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' | [
"Health",
"information",
"about",
"the",
"registered",
"service",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1859-L1897 | train |
saltstack/salt | salt/modules/consul.py | health_state | 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 | 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 | [
"def",
"health_state",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
... | 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' | [
"Returns",
"the",
"checks",
"in",
"the",
"state",
"provided",
"on",
"the",
"path",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L1952-L2000 | train |
saltstack/salt | salt/modules/consul.py | acl_delete | 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 | 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 | [
"def",
"acl_delete",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"not",... | 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' | [
"Delete",
"an",
"ACL",
"token",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2189-L2234 | train |
saltstack/salt | salt/modules/consul.py | acl_info | 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 | 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 | [
"def",
"acl_info",
"(",
"consul_url",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"not",
"consul_url",
":",
"log",
".... | 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' | [
"Information",
"about",
"an",
"ACL",
"token",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2237-L2272 | train |
saltstack/salt | salt/modules/consul.py | acl_list | 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 | 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 | [
"def",
"acl_list",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
"not",
... | List the ACL tokens.
:param consul_url: The Consul server URL.
:return: List of ACLs
CLI Example:
.. code-block:: bash
salt '*' consul.acl_list | [
"List",
"the",
"ACL",
"tokens",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2323-L2358 | train |
saltstack/salt | salt/modules/consul.py | event_fire | 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 | 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 | [
"def",
"event_fire",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_g... | 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' | [
"List",
"the",
"ACL",
"tokens",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2361-L2421 | train |
saltstack/salt | salt/modules/consul.py | event_list | 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 | 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 | [
"def",
"event_list",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
"_get_config",
"(",
")",
"if",
... | 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 | [
"List",
"the",
"recent",
"events",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/consul.py#L2424-L2459 | train |
saltstack/salt | salt/states/sysrc.py | managed | 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 | 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 | [
"def",
"managed",
"(",
"name",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment'",
":",
"''",
"}",
"# Check the current state",
"cu... | 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 | [
"Ensure",
"a",
"sysrc",
"variable",
"is",
"set",
"to",
"a",
"specific",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sysrc.py#L24-L81 | train |
saltstack/salt | salt/client/ssh/wrapper/pillar.py | get | 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) | 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) | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"''",
",",
"merge",
"=",
"False",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"if",
"merge",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"traverse_dict_and_list",
"(",
"__pillar__",... | .. 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 | [
"..",
"versionadded",
"::",
"0",
".",
"14"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L17-L64 | train |
saltstack/salt | salt/client/ssh/wrapper/pillar.py | item | 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 | 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 | [
"def",
"item",
"(",
"*",
"args",
")",
":",
"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 | [
"..",
"versionadded",
"::",
"0",
".",
"16",
".",
"2"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L67-L86 | train |
saltstack/salt | salt/client/ssh/wrapper/pillar.py | raw | 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 | 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 | [
"def",
"raw",
"(",
"key",
"=",
"None",
")",
":",
"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' | [
"Return",
"the",
"raw",
"pillar",
"data",
"that",
"is",
"available",
"in",
"the",
"module",
".",
"This",
"will",
"show",
"the",
"pillar",
"as",
"it",
"is",
"loaded",
"as",
"the",
"__pillar__",
"dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L89-L110 | train |
saltstack/salt | salt/client/ssh/wrapper/pillar.py | keys | 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() | 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() | [
"def",
"keys",
"(",
"key",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"ret",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"traverse_dict_and_list",
"(",
"__pillar__",
",",
"key",
",",
"KeyError",
",",
"delimiter",
")",
"if",
"ret",
"is",
"K... | .. 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 | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/pillar.py#L113-L140 | train |
saltstack/salt | salt/states/boto_elasticsearch_domain.py | present | 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 | 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 | [
"def",
"present",
"(",
"name",
",",
"DomainName",
",",
"ElasticsearchClusterConfig",
"=",
"None",
",",
"EBSOptions",
"=",
"None",
",",
"AccessPolicies",
"=",
"None",
",",
"SnapshotOptions",
"=",
"None",
",",
"AdvancedOptions",
"=",
"None",
",",
"Tags",
"=",
... | 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". | [
"Ensure",
"domain",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_elasticsearch_domain.py#L106-L325 | train |
saltstack/salt | salt/modules/inspectlib/dbhandle.py | DBHandleBase.open | 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() | 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() | [
"def",
"open",
"(",
"self",
",",
"new",
"=",
"False",
")",
":",
"self",
".",
"_db",
".",
"new",
"(",
")",
"if",
"new",
"else",
"self",
".",
"_db",
".",
"open",
"(",
")",
"# pylint: disable=W0106",
"self",
".",
"_run_init_queries",
"(",
")"
] | Init the database, if required. | [
"Init",
"the",
"database",
"if",
"required",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/dbhandle.py#L39-L44 | train |
saltstack/salt | salt/modules/inspectlib/dbhandle.py | DBHandleBase._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()) | python | def _run_init_queries(self):
'''
Initialization queries
'''
for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir):
self._db.create_table_from_object(obj()) | [
"def",
"_run_init_queries",
"(",
"self",
")",
":",
"for",
"obj",
"in",
"(",
"Package",
",",
"PackageCfgFile",
",",
"PayloadFile",
",",
"IgnoredDir",
",",
"AllowedDir",
")",
":",
"self",
".",
"_db",
".",
"create_table_from_object",
"(",
"obj",
"(",
")",
")"... | Initialization queries | [
"Initialization",
"queries"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/dbhandle.py#L46-L51 | train |
saltstack/salt | salt/modules/inspectlib/dbhandle.py | DBHandleBase.purge | def purge(self):
'''
Purge whole database.
'''
for table_name in self._db.list_tables():
self._db.flush(table_name)
self._run_init_queries() | python | def purge(self):
'''
Purge whole database.
'''
for table_name in self._db.list_tables():
self._db.flush(table_name)
self._run_init_queries() | [
"def",
"purge",
"(",
"self",
")",
":",
"for",
"table_name",
"in",
"self",
".",
"_db",
".",
"list_tables",
"(",
")",
":",
"self",
".",
"_db",
".",
"flush",
"(",
"table_name",
")",
"self",
".",
"_run_init_queries",
"(",
")"
] | Purge whole database. | [
"Purge",
"whole",
"database",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/inspectlib/dbhandle.py#L53-L60 | train |
saltstack/salt | salt/modules/github.py | _get_config_value | 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 | 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 | [
"def",
"_get_config_value",
"(",
"profile",
",",
"config_name",
")",
":",
"config",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"profile",
")",
"if",
"not",
"config",
":",
"raise",
"CommandExecutionError",
"(",
"'Authentication information could not be found fo... | 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. | [
"Helper",
"function",
"that",
"returns",
"a",
"profile",
"s",
"configuration",
"value",
"based",
"on",
"the",
"supplied",
"configuration",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L69-L97 | train |
saltstack/salt | salt/modules/github.py | _get_client | 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] | 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] | [
"def",
"_get_client",
"(",
"profile",
")",
":",
"token",
"=",
"_get_config_value",
"(",
"profile",
",",
"'token'",
")",
"key",
"=",
"'github.{0}:{1}'",
".",
"format",
"(",
"token",
",",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"if",
... | Return the GitHub client, cached into __context__ for performance | [
"Return",
"the",
"GitHub",
"client",
"cached",
"into",
"__context__",
"for",
"performance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L100-L115 | train |
saltstack/salt | salt/modules/github.py | list_users | 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] | 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] | [
"def",
"list_users",
"(",
"profile",
"=",
"\"github\"",
",",
"ignore_cache",
"=",
"False",
")",
":",
"org_name",
"=",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
"key",
"=",
"\"github.{0}:users\"",
".",
"format",
"(",
"org_name",
")",
"if",
... | 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' | [
"List",
"all",
"users",
"within",
"the",
"organization",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L162-L189 | train |
saltstack/salt | salt/modules/github.py | get_user | 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 | 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 | [
"def",
"get_user",
"(",
"name",
",",
"profile",
"=",
"'github'",
",",
"user_details",
"=",
"False",
")",
":",
"if",
"not",
"user_details",
"and",
"name",
"in",
"list_users",
"(",
"profile",
")",
":",
"# User is in the org, no need for additional Data",
"return",
... | 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 | [
"Get",
"a",
"GitHub",
"user",
"by",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L192-L256 | train |
saltstack/salt | salt/modules/github.py | add_user | 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' | 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' | [
"def",
"add_user",
"(",
"name",
",",
"profile",
"=",
"'github'",
")",
":",
"client",
"=",
"_get_client",
"(",
"profile",
")",
"organization",
"=",
"client",
".",
"get_organization",
"(",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"try"... | 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 | [
"Add",
"a",
"GitHub",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L259-L292 | train |
saltstack/salt | salt/modules/github.py | remove_user | 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) | 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) | [
"def",
"remove_user",
"(",
"name",
",",
"profile",
"=",
"'github'",
")",
":",
"client",
"=",
"_get_client",
"(",
"profile",
")",
"organization",
"=",
"client",
".",
"get_organization",
"(",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"t... | 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 | [
"Remove",
"a",
"Github",
"user",
"by",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L295-L326 | train |
saltstack/salt | salt/modules/github.py | get_issue | 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 | 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 | [
"def",
"get_issue",
"(",
"issue_number",
",",
"repo_name",
"=",
"None",
",",
"profile",
"=",
"'github'",
",",
"output",
"=",
"'min'",
")",
":",
"org_name",
"=",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
"if",
"repo_name",
"is",
"None",
"... | 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 | [
"Return",
"information",
"about",
"a",
"single",
"issue",
"in",
"a",
"named",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L329-L374 | train |
saltstack/salt | salt/modules/github.py | get_issue_comments | 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 | 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 | [
"def",
"get_issue_comments",
"(",
"issue_number",
",",
"repo_name",
"=",
"None",
",",
"profile",
"=",
"'github'",
",",
"since",
"=",
"None",
",",
"output",
"=",
"'min'",
")",
":",
"org_name",
"=",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
... | 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 | [
"Return",
"information",
"about",
"the",
"comments",
"for",
"a",
"given",
"issue",
"in",
"a",
"named",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L377-L437 | train |
saltstack/salt | salt/modules/github.py | get_issues | 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 | 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 | [
"def",
"get_issues",
"(",
"repo_name",
"=",
"None",
",",
"profile",
"=",
"'github'",
",",
"milestone",
"=",
"None",
",",
"state",
"=",
"'open'",
",",
"assignee",
"=",
"None",
",",
"creator",
"=",
"None",
",",
"mentioned",
"=",
"None",
",",
"labels",
"=... | 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 | [
"Returns",
"information",
"for",
"all",
"issues",
"in",
"a",
"given",
"repository",
"based",
"on",
"the",
"search",
"options",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L440-L568 | train |
saltstack/salt | salt/modules/github.py | get_milestones | 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 | 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 | [
"def",
"get_milestones",
"(",
"repo_name",
"=",
"None",
",",
"profile",
"=",
"'github'",
",",
"state",
"=",
"'open'",
",",
"sort",
"=",
"'due_on'",
",",
"direction",
"=",
"'asc'",
",",
"output",
"=",
"'min'",
",",
"per_page",
"=",
"None",
")",
":",
"or... | 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 | [
"Return",
"information",
"about",
"milestones",
"for",
"a",
"given",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L571-L650 | train |
saltstack/salt | salt/modules/github.py | get_milestone | 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 | 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 | [
"def",
"get_milestone",
"(",
"number",
"=",
"None",
",",
"name",
"=",
"None",
",",
"repo_name",
"=",
"None",
",",
"profile",
"=",
"'github'",
",",
"output",
"=",
"'min'",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"any",
"(",
"[",
"number",
",",
... | 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 | [
"Return",
"information",
"about",
"a",
"single",
"milestone",
"in",
"a",
"named",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L653-L723 | train |
saltstack/salt | salt/modules/github.py | get_repo_info | 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] | 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] | [
"def",
"get_repo_info",
"(",
"repo_name",
",",
"profile",
"=",
"'github'",
",",
"ignore_cache",
"=",
"False",
")",
":",
"org_name",
"=",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
"key",
"=",
"\"github.{0}:{1}:repo_info\"",
".",
"format",
"(",
... | 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' | [
"Return",
"information",
"for",
"a",
"given",
"repo",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L752-L800 | train |
saltstack/salt | salt/modules/github.py | get_repo_teams | 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 | 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 | [
"def",
"get_repo_teams",
"(",
"repo_name",
",",
"profile",
"=",
"'github'",
")",
":",
"ret",
"=",
"[",
"]",
"org_name",
"=",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
"client",
"=",
"_get_client",
"(",
"profile",
")",
"try",
":",
"repo",... | 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' | [
"Return",
"teams",
"belonging",
"to",
"a",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L803-L846 | train |
saltstack/salt | salt/modules/github.py | list_private_repos | 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 | 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 | [
"def",
"list_private_repos",
"(",
"profile",
"=",
"'github'",
")",
":",
"repos",
"=",
"[",
"]",
"for",
"repo",
"in",
"_get_repos",
"(",
"profile",
")",
":",
"if",
"repo",
".",
"private",
"is",
"True",
":",
"repos",
".",
"append",
"(",
"repo",
".",
"n... | 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' | [
"List",
"private",
"repositories",
"within",
"the",
"organization",
".",
"Dependent",
"upon",
"the",
"access",
"rights",
"of",
"the",
"profile",
"token",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L870-L891 | train |
saltstack/salt | salt/modules/github.py | list_public_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 | 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 | [
"def",
"list_public_repos",
"(",
"profile",
"=",
"'github'",
")",
":",
"repos",
"=",
"[",
"]",
"for",
"repo",
"in",
"_get_repos",
"(",
"profile",
")",
":",
"if",
"repo",
".",
"private",
"is",
"False",
":",
"repos",
".",
"append",
"(",
"repo",
".",
"n... | 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' | [
"List",
"public",
"repositories",
"within",
"the",
"organization",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L894-L914 | train |
saltstack/salt | salt/modules/github.py | add_repo | 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 | 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 | [
"def",
"add_repo",
"(",
"name",
",",
"description",
"=",
"None",
",",
"homepage",
"=",
"None",
",",
"private",
"=",
"None",
",",
"has_issues",
"=",
"None",
",",
"has_wiki",
"=",
"None",
",",
"has_downloads",
"=",
"None",
",",
"auto_init",
"=",
"None",
... | 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 | [
"Create",
"a",
"new",
"github",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L917-L1002 | train |
saltstack/salt | salt/modules/github.py | edit_repo | 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 | 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 | [
"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 | [
"Updates",
"an",
"existing",
"Github",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1005-L1089 | train |
saltstack/salt | salt/modules/github.py | remove_repo | 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 | 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 | [
"def",
"remove_repo",
"(",
"name",
",",
"profile",
"=",
"\"github\"",
")",
":",
"repo_info",
"=",
"get_repo_info",
"(",
"name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"repo_info",
":",
"log",
".",
"error",
"(",
"'Repo %s to be removed does not exist... | 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 | [
"Remove",
"a",
"Github",
"repository",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1092-L1125 | train |
saltstack/salt | salt/modules/github.py | add_team | 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 | 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 | [
"def",
"add_team",
"(",
"name",
",",
"description",
"=",
"None",
",",
"repo_names",
"=",
"None",
",",
"privacy",
"=",
"None",
",",
"permission",
"=",
"None",
",",
"profile",
"=",
"\"github\"",
")",
":",
"try",
":",
"client",
"=",
"_get_client",
"(",
"p... | 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 | [
"Create",
"a",
"new",
"Github",
"team",
"within",
"an",
"organization",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1148-L1210 | train |
saltstack/salt | salt/modules/github.py | edit_team | 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 | 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 | [
"def",
"edit_team",
"(",
"name",
",",
"description",
"=",
"None",
",",
"privacy",
"=",
"None",
",",
"permission",
"=",
"None",
",",
"profile",
"=",
"\"github\"",
")",
":",
"team",
"=",
"get_team",
"(",
"name",
",",
"profile",
"=",
"profile",
")",
"if",... | 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 | [
"Updates",
"an",
"existing",
"Github",
"team",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1213-L1274 | train |
saltstack/salt | salt/modules/github.py | remove_team | 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 | 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 | [
"def",
"remove_team",
"(",
"name",
",",
"profile",
"=",
"\"github\"",
")",
":",
"team_info",
"=",
"get_team",
"(",
"name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"team_info",
":",
"log",
".",
"error",
"(",
"'Team %s to be removed does not exist.'",
... | 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 | [
"Remove",
"a",
"github",
"team",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1277-L1309 | train |
saltstack/salt | salt/modules/github.py | list_team_repos | 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 [] | 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 [] | [
"def",
"list_team_repos",
"(",
"team_name",
",",
"profile",
"=",
"\"github\"",
",",
"ignore_cache",
"=",
"False",
")",
":",
"cached_team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"cached_team",
":",
"log",
".",
... | 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 | [
"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",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1312-L1367 | train |
saltstack/salt | salt/modules/github.py | add_team_repo | 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 | 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 | [
"def",
"add_team_repo",
"(",
"repo_name",
",",
"team_name",
",",
"profile",
"=",
"\"github\"",
",",
"permission",
"=",
"None",
")",
":",
"team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"team",
":",
"log",
".",... | 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 | [
"Adds",
"a",
"repository",
"to",
"a",
"team",
"with",
"team_name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1370-L1423 | train |
saltstack/salt | salt/modules/github.py | remove_team_repo | 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) | 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) | [
"def",
"remove_team_repo",
"(",
"repo_name",
",",
"team_name",
",",
"profile",
"=",
"\"github\"",
")",
":",
"team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"team",
":",
"log",
".",
"error",
"(",
"'Team %s does n... | 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 | [
"Removes",
"a",
"repository",
"from",
"a",
"team",
"with",
"team_name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1426-L1462 | train |
saltstack/salt | salt/modules/github.py | list_team_members | 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 [] | 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 [] | [
"def",
"list_team_members",
"(",
"team_name",
",",
"profile",
"=",
"\"github\"",
",",
"ignore_cache",
"=",
"False",
")",
":",
"cached_team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"cached_team",
":",
"log",
".",
... | 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 | [
"Gets",
"the",
"names",
"of",
"team",
"members",
"in",
"lower",
"case",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1465-L1508 | train |
saltstack/salt | salt/modules/github.py | list_members_without_mfa | 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] | 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] | [
"def",
"list_members_without_mfa",
"(",
"profile",
"=",
"\"github\"",
",",
"ignore_cache",
"=",
"False",
")",
":",
"key",
"=",
"\"github.{0}:non_mfa_users\"",
".",
"format",
"(",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"if",
"key",
"not... | 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 | [
"List",
"all",
"members",
"(",
"in",
"lower",
"case",
")",
"without",
"MFA",
"turned",
"on",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1511-L1547 | train |
saltstack/salt | salt/modules/github.py | is_team_member | 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) | 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) | [
"def",
"is_team_member",
"(",
"name",
",",
"team_name",
",",
"profile",
"=",
"\"github\"",
")",
":",
"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 | [
"Returns",
"True",
"if",
"the",
"github",
"user",
"is",
"in",
"the",
"team",
"with",
"team_name",
"or",
"False",
"otherwise",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1550-L1572 | train |
saltstack/salt | salt/modules/github.py | add_team_member | 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 | 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 | [
"def",
"add_team_member",
"(",
"name",
",",
"team_name",
",",
"profile",
"=",
"\"github\"",
")",
":",
"team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"team",
":",
"log",
".",
"error",
"(",
"'Team %s does not exi... | 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 | [
"Adds",
"a",
"team",
"member",
"to",
"a",
"team",
"with",
"team_name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1575-L1623 | train |
saltstack/salt | salt/modules/github.py | remove_team_member | 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) | 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) | [
"def",
"remove_team_member",
"(",
"name",
",",
"team_name",
",",
"profile",
"=",
"\"github\"",
")",
":",
"team",
"=",
"get_team",
"(",
"team_name",
",",
"profile",
"=",
"profile",
")",
"if",
"not",
"team",
":",
"log",
".",
"error",
"(",
"'Team %s does not ... | 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 | [
"Removes",
"a",
"team",
"member",
"from",
"a",
"team",
"with",
"team_name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1626-L1668 | train |
saltstack/salt | salt/modules/github.py | list_teams | 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] | 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] | [
"def",
"list_teams",
"(",
"profile",
"=",
"\"github\"",
",",
"ignore_cache",
"=",
"False",
")",
":",
"key",
"=",
"'github.{0}:teams'",
".",
"format",
"(",
"_get_config_value",
"(",
"profile",
",",
"'org_name'",
")",
")",
"if",
"key",
"not",
"in",
"__context_... | 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 | [
"Lists",
"all",
"teams",
"with",
"the",
"organization",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1671-L1714 | train |
saltstack/salt | salt/modules/github.py | get_prs | 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 | 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 | [
"def",
"get_prs",
"(",
"repo_name",
"=",
"None",
",",
"profile",
"=",
"'github'",
",",
"state",
"=",
"'open'",
",",
"head",
"=",
"None",
",",
"base",
"=",
"None",
",",
"sort",
"=",
"'created'",
",",
"direction",
"=",
"'desc'",
",",
"output",
"=",
"'m... | 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 | [
"Returns",
"information",
"for",
"all",
"pull",
"requests",
"in",
"a",
"given",
"repository",
"based",
"on",
"the",
"search",
"options",
"provided",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1717-L1813 | train |
saltstack/salt | salt/modules/github.py | _format_pr | 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 | 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 | [
"def",
"_format_pr",
"(",
"pr_",
")",
":",
"ret",
"=",
"{",
"'id'",
":",
"pr_",
".",
"get",
"(",
"'id'",
")",
",",
"'pr_number'",
":",
"pr_",
".",
"get",
"(",
"'number'",
")",
",",
"'state'",
":",
"pr_",
".",
"get",
"(",
"'state'",
")",
",",
"'... | Helper function to format API return information into a more manageable
and useful dictionary for pull request information.
pr_
The pull request to format. | [
"Helper",
"function",
"to",
"format",
"API",
"return",
"information",
"into",
"a",
"more",
"manageable",
"and",
"useful",
"dictionary",
"for",
"pull",
"request",
"information",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1816-L1832 | train |
saltstack/salt | salt/modules/github.py | _format_issue | 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 | 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 | [
"def",
"_format_issue",
"(",
"issue",
")",
":",
"ret",
"=",
"{",
"'id'",
":",
"issue",
".",
"get",
"(",
"'id'",
")",
",",
"'issue_number'",
":",
"issue",
".",
"get",
"(",
"'number'",
")",
",",
"'state'",
":",
"issue",
".",
"get",
"(",
"'state'",
")... | Helper function to format API return information into a more manageable
and useful dictionary for issue information.
issue
The issue to format. | [
"Helper",
"function",
"to",
"format",
"API",
"return",
"information",
"into",
"a",
"more",
"manageable",
"and",
"useful",
"dictionary",
"for",
"issue",
"information",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1835-L1867 | train |
saltstack/salt | salt/modules/github.py | _query | 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 | 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 | [
"def",
"_query",
"(",
"profile",
",",
"action",
"=",
"None",
",",
"command",
"=",
"None",
",",
"args",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"header_dict",
"=",
"None",
",",
"data",
"=",
"None",
",",
"url",
"=",
"'https://api.github.com/'",
",... | Make a web call to the GitHub API and deal with paginated results. | [
"Make",
"a",
"web",
"call",
"to",
"the",
"GitHub",
"API",
"and",
"deal",
"with",
"paginated",
"results",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/github.py#L1870-L1959 | train |
saltstack/salt | salt/states/snapper.py | _get_baseline_from_tag | 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 | 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 | [
"def",
"_get_baseline_from_tag",
"(",
"config",
",",
"tag",
")",
":",
"last_snapshot",
"=",
"None",
"for",
"snapshot",
"in",
"__salt__",
"[",
"'snapper.list_snapshots'",
"]",
"(",
"config",
")",
":",
"if",
"tag",
"==",
"snapshot",
"[",
"'userdata'",
"]",
"."... | Returns the last created baseline snapshot marked with `tag` | [
"Returns",
"the",
"last",
"created",
"baseline",
"snapshot",
"marked",
"with",
"tag"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/snapper.py#L122-L131 | train |
saltstack/salt | salt/states/snapper.py | baseline_snapshot | 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 | 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 | [
"def",
"baseline_snapshot",
"(",
"name",
",",
"number",
"=",
"None",
",",
"tag",
"=",
"None",
",",
"include_diff",
"=",
"True",
",",
"config",
"=",
"'root'",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"not",
"ignore",
":",
"ignore",
"=",
"[",
"]",
... | 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) | [
"Enforces",
"that",
"no",
"file",
"is",
"modified",
"comparing",
"against",
"a",
"previously",
"defined",
"snapshot",
"identified",
"by",
"number",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/snapper.py#L134-L219 | train |
saltstack/salt | salt/utils/fsutils.py | _verify_run | 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']) | 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']) | [
"def",
"_verify_run",
"(",
"out",
",",
"cmd",
"=",
"None",
")",
":",
"if",
"out",
".",
"get",
"(",
"'retcode'",
",",
"0",
")",
"and",
"out",
"[",
"'stderr'",
"]",
":",
"if",
"cmd",
":",
"log",
".",
"debug",
"(",
"'Command: \\'%s\\''",
",",
"cmd",
... | Crash to the log if command execution was not successful. | [
"Crash",
"to",
"the",
"log",
"if",
"command",
"execution",
"was",
"not",
"successful",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L25-L36 | train |
saltstack/salt | salt/utils/fsutils.py | _get_mounts | 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 | 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 | [
"def",
"_get_mounts",
"(",
"fs_type",
"=",
"None",
")",
":",
"mounts",
"=",
"{",
"}",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"'/proc/mounts'",
")",
"as",
"fhr",
":",
"for",
"line",
"in",
"fhr",
".",
"readlines",
"(",
")",
":... | List mounted filesystems. | [
"List",
"mounted",
"filesystems",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L39-L60 | train |
saltstack/salt | salt/utils/fsutils.py | _blkid_output | 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 | 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 | [
"def",
"_blkid_output",
"(",
"out",
",",
"fs_type",
"=",
"None",
")",
":",
"flt",
"=",
"lambda",
"data",
":",
"[",
"el",
"for",
"el",
"in",
"data",
"if",
"el",
".",
"strip",
"(",
")",
"]",
"data",
"=",
"{",
"}",
"for",
"dev_meta",
"in",
"flt",
... | Parse blkid output. | [
"Parse",
"blkid",
"output",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L64-L86 | train |
saltstack/salt | salt/utils/fsutils.py | _blkid | 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 | 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 | [
"def",
"_blkid",
"(",
"fs_type",
"=",
"None",
")",
":",
"flt",
"=",
"lambda",
"data",
":",
"[",
"el",
"for",
"el",
"in",
"data",
"if",
"el",
".",
"strip",
"(",
")",
"]",
"data",
"=",
"dict",
"(",
")",
"for",
"dev_meta",
"in",
"flt",
"(",
"os",
... | Return available media devices.
:param fs_type: Filter only devices that are formatted by that file system. | [
"Return",
"available",
"media",
"devices",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L89-L114 | train |
saltstack/salt | salt/utils/fsutils.py | _is_device | 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' | 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' | [
"def",
"_is_device",
"(",
"path",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'file -i {0}'",
".",
"format",
"(",
"path",
")",
")",
"_verify_run",
"(",
"out",
")",
"# Always [device, mime, charset]. See (file --help)",
"return",
"re",
".",... | Return True if path is a physical device. | [
"Return",
"True",
"if",
"path",
"is",
"a",
"physical",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/fsutils.py#L117-L125 | train |
saltstack/salt | salt/returners/mattermost_returner.py | returner | 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 | 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 | [
"def",
"returner",
"(",
"ret",
")",
":",
"_options",
"=",
"_get_options",
"(",
"ret",
")",
"api_url",
"=",
"_options",
".",
"get",
"(",
"'api_url'",
")",
"channel",
"=",
"_options",
".",
"get",
"(",
"'channel'",
")",
"username",
"=",
"_options",
".",
"... | Send an mattermost message with the data | [
"Send",
"an",
"mattermost",
"message",
"with",
"the",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mattermost_returner.py#L96-L130 | train |
saltstack/salt | salt/returners/mattermost_returner.py | event_return | 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 | 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 | [
"def",
"event_return",
"(",
"events",
")",
":",
"_options",
"=",
"_get_options",
"(",
")",
"api_url",
"=",
"_options",
".",
"get",
"(",
"'api_url'",
")",
"channel",
"=",
"_options",
".",
"get",
"(",
"'channel'",
")",
"username",
"=",
"_options",
".",
"ge... | Send the events to a mattermost room.
:param events: List of events
:return: Boolean if messages were sent successfully. | [
"Send",
"the",
"events",
"to",
"a",
"mattermost",
"room",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mattermost_returner.py#L133-L162 | train |
saltstack/salt | salt/returners/mattermost_returner.py | post_message | 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) | 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) | [
"def",
"post_message",
"(",
"channel",
",",
"message",
",",
"username",
",",
"api_url",
",",
"hook",
")",
":",
"parameters",
"=",
"dict",
"(",
")",
"if",
"channel",
":",
"parameters",
"[",
"'channel'",
"]",
"=",
"channel",
"if",
"username",
":",
"paramet... | 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. | [
"Send",
"a",
"message",
"to",
"a",
"mattermost",
"room",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/mattermost_returner.py#L165-L193 | train |
saltstack/salt | salt/modules/zookeeper.py | create | 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) | 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) | [
"def",
"create",
"(",
"path",
",",
"value",
"=",
"''",
",",
"acls",
"=",
"None",
",",
"ephemeral",
"=",
"False",
",",
"sequence",
"=",
"False",
",",
"makepath",
"=",
"False",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=... | 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 | [
"Create",
"Znode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L134-L187 | train |
saltstack/salt | salt/modules/zookeeper.py | ensure_path | 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) | 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) | [
"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 | [
"Ensure",
"Znode",
"path",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L190-L231 | train |
saltstack/salt | salt/modules/zookeeper.py | exists | 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)) | 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)) | [
"def",
"exists",
"(",
"path",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"default_acl",
"=",
"None",
")",
":",
"conn",
"=",
"_get_zk_conn",
"(",... | 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 | [
"Check",
"if",
"path",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L234-L268 | train |
saltstack/salt | salt/modules/zookeeper.py | get | 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) | 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) | [
"def",
"get",
"(",
"path",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"default_acl",
"=",
"None",
")",
":",
"conn",
"=",
"_get_zk_conn",
"(",
... | 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 | [
"Get",
"value",
"saved",
"in",
"znode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L271-L306 | train |
saltstack/salt | salt/modules/zookeeper.py | get_children | 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 [] | 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 [] | [
"def",
"get_children",
"(",
"path",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"default_acl",
"=",
"None",
")",
":",
"conn",
"=",
"_get_zk_conn",
... | 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 | [
"Get",
"children",
"in",
"znode",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L309-L344 | train |
saltstack/salt | salt/modules/zookeeper.py | set | 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) | 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) | [
"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 | [
"Update",
"znode",
"with",
"new",
"value"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L347-L388 | train |
saltstack/salt | salt/modules/zookeeper.py | get_acls | 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] | 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] | [
"def",
"get_acls",
"(",
"path",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"default_acl",
"=",
"None",
")",
":",
"conn",
"=",
"_get_zk_conn",
"(... | 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 | [
"Get",
"acls",
"on",
"a",
"znode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L391-L425 | train |
saltstack/salt | salt/modules/zookeeper.py | set_acls | 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) | 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) | [
"def",
"set_acls",
"(",
"path",
",",
"acls",
",",
"version",
"=",
"-",
"1",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"default_acl",
"=",
"No... | 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 | [
"Set",
"acls",
"on",
"a",
"znode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L428-L474 | train |
saltstack/salt | salt/modules/zookeeper.py | delete | 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) | 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) | [
"def",
"delete",
"(",
"path",
",",
"version",
"=",
"-",
"1",
",",
"recursive",
"=",
"False",
",",
"profile",
"=",
"None",
",",
"hosts",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"defau... | 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 | [
"Delete",
"znode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L477-L515 | train |
saltstack/salt | salt/modules/zookeeper.py | make_digest_acl | 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) | 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) | [
"def",
"make_digest_acl",
"(",
"username",
",",
"password",
",",
"read",
"=",
"False",
",",
"write",
"=",
"False",
",",
"create",
"=",
"False",
",",
"delete",
"=",
"False",
",",
"admin",
"=",
"False",
",",
"allperms",
"=",
"False",
")",
":",
"return",
... | 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 | [
"Generate",
"acl",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/zookeeper.py#L518-L555 | train |
saltstack/salt | salt/utils/mattermost.py | query | 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 | 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 | [
"def",
"query",
"(",
"hook",
"=",
"None",
",",
"api_url",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"method",
"=",
"'POST'",
"ret",
"=",
"{",
"'message'",
":",
"''",
",",
"'res'",
":",
"True",
"}",
"base_url",
"=",
"_urljoin",
"(",
"api_url"... | 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. | [
"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",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/mattermost.py#L29-L72 | train |
saltstack/salt | salt/pillar/confidant.py | ext_pillar | 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 | 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 | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"profile",
"=",
"None",
")",
":",
"if",
"profile",
"is",
"None",
":",
"profile",
"=",
"{",
"}",
"# default to returning failure",
"ret",
"=",
"{",
"'credentials_result'",
":",
"False",
",",
"'credent... | Read pillar data from Confidant via its API. | [
"Read",
"pillar",
"data",
"from",
"Confidant",
"via",
"its",
"API",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/confidant.py#L70-L123 | train |
saltstack/salt | salt/log/setup.py | setup_temp_logger | 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 | 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 | [
"def",
"setup_temp_logger",
"(",
"log_level",
"=",
"'error'",
")",
":",
"if",
"is_temp_logging_configured",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warning",
"(",
"'Temporary logging is already configured'",
")",
"return",
"if",
"lo... | Setup the temporary console logger | [
"Setup",
"the",
"temporary",
"console",
"logger"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L457-L508 | train |
saltstack/salt | salt/log/setup.py | setup_console_logger | 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 | 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 | [
"def",
"setup_console_logger",
"(",
"log_level",
"=",
"'error'",
",",
"log_format",
"=",
"None",
",",
"date_format",
"=",
"None",
")",
":",
"if",
"is_console_configured",
"(",
")",
":",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
".",
"warning",
"(",
... | Setup the console logger | [
"Setup",
"the",
"console",
"logger"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L511-L559 | train |
saltstack/salt | salt/log/setup.py | setup_logfile_logger | 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 | 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 | [
"def",
"setup_logfile_logger",
"(",
"log_path",
",",
"log_level",
"=",
"'error'",
",",
"log_format",
"=",
"None",
",",
"date_format",
"=",
"None",
",",
"max_bytes",
"=",
"0",
",",
"backup_count",
"=",
"0",
")",
":",
"if",
"is_logfile_configured",
"(",
")",
... | 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. | [
"Setup",
"the",
"logfile",
"logger"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L562-L739 | train |
saltstack/salt | salt/log/setup.py | setup_extended_logging | 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 | 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 | [
"def",
"setup_extended_logging",
"(",
"opts",
")",
":",
"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 referenc... | Setup any additional logging handlers, internal or external | [
"Setup",
"any",
"additional",
"logging",
"handlers",
"internal",
"or",
"external"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L742-L824 | train |
saltstack/salt | salt/log/setup.py | set_multiprocessing_logging_level_by_opts | 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) | 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) | [
"def",
"set_multiprocessing_logging_level_by_opts",
"(",
"opts",
")",
":",
"global",
"__MP_LOGGING_LEVEL",
"log_levels",
"=",
"[",
"LOG_LEVELS",
".",
"get",
"(",
"opts",
".",
"get",
"(",
"'log_level'",
",",
"''",
")",
".",
"lower",
"(",
")",
",",
"logging",
... | This will set the multiprocessing logging level to the lowest
logging level of all the types of logging that are configured. | [
"This",
"will",
"set",
"the",
"multiprocessing",
"logging",
"level",
"to",
"the",
"lowest",
"logging",
"level",
"of",
"all",
"the",
"types",
"of",
"logging",
"that",
"are",
"configured",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L854-L870 | train |
saltstack/salt | salt/log/setup.py | setup_multiprocessing_logging | 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() | 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() | [
"def",
"setup_multiprocessing_logging",
"(",
"queue",
"=",
"None",
")",
":",
"from",
"salt",
".",
"utils",
".",
"platform",
"import",
"is_windows",
"global",
"__MP_LOGGING_CONFIGURED",
"global",
"__MP_LOGGING_QUEUE_HANDLER",
"if",
"__MP_IN_MAINPROCESS",
"is",
"True",
... | This code should be called from within a running multiprocessing
process instance. | [
"This",
"code",
"should",
"be",
"called",
"from",
"within",
"a",
"running",
"multiprocessing",
"process",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L899-L950 | train |
saltstack/salt | salt/log/setup.py | set_logger_level | 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)
) | 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)
) | [
"def",
"set_logger_level",
"(",
"logger_name",
",",
"log_level",
"=",
"'error'",
")",
":",
"logging",
".",
"getLogger",
"(",
"logger_name",
")",
".",
"setLevel",
"(",
"LOG_LEVELS",
".",
"get",
"(",
"log_level",
".",
"lower",
"(",
")",
",",
"logging",
".",
... | Tweak a specific logger's logging level | [
"Tweak",
"a",
"specific",
"logger",
"s",
"logging",
"level"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1060-L1066 | train |
saltstack/salt | salt/log/setup.py | patch_python_logging_handlers | 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 | 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 | [
"def",
"patch_python_logging_handlers",
"(",
")",
":",
"logging",
".",
"StreamHandler",
"=",
"StreamHandler",
"logging",
".",
"FileHandler",
"=",
"FileHandler",
"logging",
".",
"handlers",
".",
"SysLogHandler",
"=",
"SysLogHandler",
"logging",
".",
"handlers",
".",
... | Patch the python logging handlers with out mixed-in classes | [
"Patch",
"the",
"python",
"logging",
"handlers",
"with",
"out",
"mixed",
"-",
"in",
"classes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1069-L1079 | train |
saltstack/salt | salt/log/setup.py | __remove_null_logging_handler | 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 | 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 | [
"def",
"__remove_null_logging_handler",
"(",
")",
":",
"global",
"LOGGING_NULL_HANDLER",
"if",
"LOGGING_NULL_HANDLER",
"is",
"None",
":",
"# Already removed",
"return",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"for",
"handler",
"in",
"root_logger",
... | This function will run once the temporary logging has been configured. It
just removes the NullHandler from the logging handlers. | [
"This",
"function",
"will",
"run",
"once",
"the",
"temporary",
"logging",
"has",
"been",
"configured",
".",
"It",
"just",
"removes",
"the",
"NullHandler",
"from",
"the",
"logging",
"handlers",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1132-L1149 | train |
saltstack/salt | salt/log/setup.py | __remove_queue_logging_handler | 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 | 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 | [
"def",
"__remove_queue_logging_handler",
"(",
")",
":",
"global",
"LOGGING_STORE_HANDLER",
"if",
"LOGGING_STORE_HANDLER",
"is",
"None",
":",
"# Already removed",
"return",
"root_logger",
"=",
"logging",
".",
"getLogger",
"(",
")",
"for",
"handler",
"in",
"root_logger"... | This function will run once the additional loggers have been synchronized.
It just removes the QueueLoggingHandler from the logging handlers. | [
"This",
"function",
"will",
"run",
"once",
"the",
"additional",
"loggers",
"have",
"been",
"synchronized",
".",
"It",
"just",
"removes",
"the",
"QueueLoggingHandler",
"from",
"the",
"logging",
"handlers",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1152-L1169 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.