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/runners/state.py | orchestrate_high | def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs):
'''
Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_high '{
stage_one:
{salt.state: [{tgt: "db*"}, {sls: postgres_setup}]},
stage_two:
{salt.state: [{tgt: "web*"}, {sls: apache_setup}, {
require: [{salt: stage_one}],
}]},
}'
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary'
)
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
running = minion.functions['state.high'](
data,
test=None,
queue=False,
pillar=pillar,
**kwargs)
ret = {minion.opts['id']: running}
__jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress')
return ret | python | def orchestrate_high(data, test=None, queue=False, pillar=None, **kwargs):
'''
Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_high '{
stage_one:
{salt.state: [{tgt: "db*"}, {sls: postgres_setup}]},
stage_two:
{salt.state: [{tgt: "web*"}, {sls: apache_setup}, {
require: [{salt: stage_one}],
}]},
}'
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary'
)
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
running = minion.functions['state.high'](
data,
test=None,
queue=False,
pillar=pillar,
**kwargs)
ret = {minion.opts['id']: running}
__jid_event__.fire_event({'data': ret, 'outputter': 'highstate'}, 'progress')
return ret | [
"def",
"orchestrate_high",
"(",
"data",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"pillar",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"pillar",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"pillar",
",",
"dict",
... | Execute a single state orchestration routine
.. versionadded:: 2015.5.0
CLI Example:
.. code-block:: bash
salt-run state.orchestrate_high '{
stage_one:
{salt.state: [{tgt: "db*"}, {sls: postgres_setup}]},
stage_two:
{salt.state: [{tgt: "web*"}, {sls: apache_setup}, {
require: [{salt: stage_one}],
}]},
}' | [
"Execute",
"a",
"single",
"state",
"orchestration",
"routine"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L173-L206 | train |
saltstack/salt | salt/runners/state.py | orchestrate_show_sls | def orchestrate_show_sls(mods,
saltenv='base',
test=None,
queue=False,
pillar=None,
pillarenv=None,
pillar_enc=None):
'''
Display the state data from a specific sls, or list of sls files, after
being render using the master minion.
Note, the master minion adds a "_master" suffix to it's minion id.
.. seealso:: The state.show_sls module function
CLI Example:
.. code-block:: bash
salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }'
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary')
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
running = minion.functions['state.show_sls'](
mods,
test,
queue,
pillar=pillar,
pillarenv=pillarenv,
pillar_enc=pillar_enc,
saltenv=saltenv)
ret = {minion.opts['id']: running}
return ret | python | def orchestrate_show_sls(mods,
saltenv='base',
test=None,
queue=False,
pillar=None,
pillarenv=None,
pillar_enc=None):
'''
Display the state data from a specific sls, or list of sls files, after
being render using the master minion.
Note, the master minion adds a "_master" suffix to it's minion id.
.. seealso:: The state.show_sls module function
CLI Example:
.. code-block:: bash
salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }'
'''
if pillar is not None and not isinstance(pillar, dict):
raise SaltInvocationError(
'Pillar data must be formatted as a dictionary')
__opts__['file_client'] = 'local'
minion = salt.minion.MasterMinion(__opts__)
running = minion.functions['state.show_sls'](
mods,
test,
queue,
pillar=pillar,
pillarenv=pillarenv,
pillar_enc=pillar_enc,
saltenv=saltenv)
ret = {minion.opts['id']: running}
return ret | [
"def",
"orchestrate_show_sls",
"(",
"mods",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"pillar",
"=",
"None",
",",
"pillarenv",
"=",
"None",
",",
"pillar_enc",
"=",
"None",
")",
":",
"if",
"pillar",
"is",
... | Display the state data from a specific sls, or list of sls files, after
being render using the master minion.
Note, the master minion adds a "_master" suffix to it's minion id.
.. seealso:: The state.show_sls module function
CLI Example:
.. code-block:: bash
salt-run state.orch_show_sls my-orch-formula.my-orch-state 'pillar={ nodegroup: ng1 }' | [
"Display",
"the",
"state",
"data",
"from",
"a",
"specific",
"sls",
"or",
"list",
"of",
"sls",
"files",
"after",
"being",
"render",
"using",
"the",
"master",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L209-L245 | train |
saltstack/salt | salt/runners/state.py | event | def event(tagmatch='*',
count=-1,
quiet=False,
sock_dir=None,
pretty=False,
node='master'):
r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2014.7.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful for utilizing Salt's event bus from shell scripts or for
taking simple actions directly from the CLI.
Enable debug logging to see ignored events.
:param tagmatch: the event is written to stdout for each tag that matches
this glob or regular expression.
:param count: this number is decremented for each event that matches the
``tagmatch`` parameter; pass ``-1`` to listen forever.
:param quiet: do not print to stdout; just block
:param sock_dir: path to the Salt master's event socket file.
:param pretty: Output the JSON all on a single line if ``False`` (useful
for shell tools); pretty-print the JSON output if ``True``.
:param node: Watch the minion-side or master-side event bus.
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
# Reboot a minion and run highstate when it comes back online
salt 'jerry' system.reboot && \\
salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\
salt 'jerry' state.highstate
# Reboot multiple minions and run highstate when all are back online
salt -L 'kevin,stewart,dave' system.reboot && \\
salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\
salt -L 'kevin,stewart,dave' state.highstate
# Watch the event bus forever in a shell while-loop.
salt-run state.event | while read -r tag data; do
echo $tag
echo $data | jq --color-output .
done
.. seealso::
See :blob:`tests/eventlisten.sh` for an example of usage within a shell
script.
'''
statemod = salt.loader.raw_mod(__opts__, 'state', None)
return statemod['state.event'](
tagmatch=tagmatch,
count=count,
quiet=quiet,
sock_dir=sock_dir,
pretty=pretty,
node=node) | python | def event(tagmatch='*',
count=-1,
quiet=False,
sock_dir=None,
pretty=False,
node='master'):
r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2014.7.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful for utilizing Salt's event bus from shell scripts or for
taking simple actions directly from the CLI.
Enable debug logging to see ignored events.
:param tagmatch: the event is written to stdout for each tag that matches
this glob or regular expression.
:param count: this number is decremented for each event that matches the
``tagmatch`` parameter; pass ``-1`` to listen forever.
:param quiet: do not print to stdout; just block
:param sock_dir: path to the Salt master's event socket file.
:param pretty: Output the JSON all on a single line if ``False`` (useful
for shell tools); pretty-print the JSON output if ``True``.
:param node: Watch the minion-side or master-side event bus.
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
# Reboot a minion and run highstate when it comes back online
salt 'jerry' system.reboot && \\
salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\
salt 'jerry' state.highstate
# Reboot multiple minions and run highstate when all are back online
salt -L 'kevin,stewart,dave' system.reboot && \\
salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\
salt -L 'kevin,stewart,dave' state.highstate
# Watch the event bus forever in a shell while-loop.
salt-run state.event | while read -r tag data; do
echo $tag
echo $data | jq --color-output .
done
.. seealso::
See :blob:`tests/eventlisten.sh` for an example of usage within a shell
script.
'''
statemod = salt.loader.raw_mod(__opts__, 'state', None)
return statemod['state.event'](
tagmatch=tagmatch,
count=count,
quiet=quiet,
sock_dir=sock_dir,
pretty=pretty,
node=node) | [
"def",
"event",
"(",
"tagmatch",
"=",
"'*'",
",",
"count",
"=",
"-",
"1",
",",
"quiet",
"=",
"False",
",",
"sock_dir",
"=",
"None",
",",
"pretty",
"=",
"False",
",",
"node",
"=",
"'master'",
")",
":",
"statemod",
"=",
"salt",
".",
"loader",
".",
... | r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2014.7.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful for utilizing Salt's event bus from shell scripts or for
taking simple actions directly from the CLI.
Enable debug logging to see ignored events.
:param tagmatch: the event is written to stdout for each tag that matches
this glob or regular expression.
:param count: this number is decremented for each event that matches the
``tagmatch`` parameter; pass ``-1`` to listen forever.
:param quiet: do not print to stdout; just block
:param sock_dir: path to the Salt master's event socket file.
:param pretty: Output the JSON all on a single line if ``False`` (useful
for shell tools); pretty-print the JSON output if ``True``.
:param node: Watch the minion-side or master-side event bus.
.. versionadded:: 2016.3.0
CLI Examples:
.. code-block:: bash
# Reboot a minion and run highstate when it comes back online
salt 'jerry' system.reboot && \\
salt-run state.event 'salt/minion/jerry/start' count=1 quiet=True && \\
salt 'jerry' state.highstate
# Reboot multiple minions and run highstate when all are back online
salt -L 'kevin,stewart,dave' system.reboot && \\
salt-run state.event 'salt/minion/*/start' count=3 quiet=True && \\
salt -L 'kevin,stewart,dave' state.highstate
# Watch the event bus forever in a shell while-loop.
salt-run state.event | while read -r tag data; do
echo $tag
echo $data | jq --color-output .
done
.. seealso::
See :blob:`tests/eventlisten.sh` for an example of usage within a shell
script. | [
"r",
"Watch",
"Salt",
"s",
"event",
"bus",
"and",
"block",
"until",
"the",
"given",
"tag",
"is",
"matched"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/state.py#L251-L313 | train |
saltstack/salt | salt/modules/smtp.py | send_msg | def send_msg(recipient,
message,
subject='Message from Salt',
sender=None,
server=None,
use_ssl='True',
username=None,
password=None,
profile=None,
attachments=None):
'''
Send a message to an SMTP recipient. Designed for use in states.
CLI Examples:
.. code-block:: bash
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' profile='my-smtp-account'
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com'
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com' attachments="['/var/log/messages']"
'''
if profile:
creds = __salt__['config.option'](profile)
server = creds.get('smtp.server')
use_ssl = creds.get('smtp.tls')
sender = creds.get('smtp.sender')
username = creds.get('smtp.username')
password = creds.get('smtp.password')
if attachments:
msg = email.mime.multipart.MIMEMultipart()
msg.attach(email.mime.text.MIMEText(message))
else:
msg = email.mime.text.MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
recipients = [r.strip() for r in recipient.split(',')]
try:
if use_ssl in ['True', 'true']:
smtpconn = smtplib.SMTP_SSL(server)
else:
smtpconn = smtplib.SMTP(server)
except socket.gaierror as _error:
log.debug("Exception: %s", _error)
return False
if use_ssl not in ('True', 'true'):
smtpconn.ehlo()
if smtpconn.has_extn('STARTTLS'):
try:
smtpconn.starttls()
except smtplib.SMTPHeloError:
log.debug("The server didn’t reply properly \
to the HELO greeting.")
return False
except smtplib.SMTPException:
log.debug("The server does not support the STARTTLS extension.")
return False
except RuntimeError:
log.debug("SSL/TLS support is not available \
to your Python interpreter.")
return False
smtpconn.ehlo()
if username and password:
try:
smtpconn.login(username, password)
except smtplib.SMTPAuthenticationError as _error:
log.debug("SMTP Authentication Failure")
return False
if attachments:
for f in attachments:
name = os.path.basename(f)
with salt.utils.files.fopen(f, 'rb') as fin:
att = email.mime.application.MIMEApplication(fin.read(), Name=name)
att['Content-Disposition'] = 'attachment; filename="{0}"'.format(name)
msg.attach(att)
try:
smtpconn.sendmail(sender, recipients, msg.as_string())
except smtplib.SMTPRecipientsRefused:
log.debug("All recipients were refused.")
return False
except smtplib.SMTPHeloError:
log.debug("The server didn’t reply properly to the HELO greeting.")
return False
except smtplib.SMTPSenderRefused:
log.debug("The server didn’t accept the %s.", sender)
return False
except smtplib.SMTPDataError:
log.debug("The server replied with an unexpected error code.")
return False
smtpconn.quit()
return True | python | def send_msg(recipient,
message,
subject='Message from Salt',
sender=None,
server=None,
use_ssl='True',
username=None,
password=None,
profile=None,
attachments=None):
'''
Send a message to an SMTP recipient. Designed for use in states.
CLI Examples:
.. code-block:: bash
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' profile='my-smtp-account'
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com'
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com' attachments="['/var/log/messages']"
'''
if profile:
creds = __salt__['config.option'](profile)
server = creds.get('smtp.server')
use_ssl = creds.get('smtp.tls')
sender = creds.get('smtp.sender')
username = creds.get('smtp.username')
password = creds.get('smtp.password')
if attachments:
msg = email.mime.multipart.MIMEMultipart()
msg.attach(email.mime.text.MIMEText(message))
else:
msg = email.mime.text.MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
recipients = [r.strip() for r in recipient.split(',')]
try:
if use_ssl in ['True', 'true']:
smtpconn = smtplib.SMTP_SSL(server)
else:
smtpconn = smtplib.SMTP(server)
except socket.gaierror as _error:
log.debug("Exception: %s", _error)
return False
if use_ssl not in ('True', 'true'):
smtpconn.ehlo()
if smtpconn.has_extn('STARTTLS'):
try:
smtpconn.starttls()
except smtplib.SMTPHeloError:
log.debug("The server didn’t reply properly \
to the HELO greeting.")
return False
except smtplib.SMTPException:
log.debug("The server does not support the STARTTLS extension.")
return False
except RuntimeError:
log.debug("SSL/TLS support is not available \
to your Python interpreter.")
return False
smtpconn.ehlo()
if username and password:
try:
smtpconn.login(username, password)
except smtplib.SMTPAuthenticationError as _error:
log.debug("SMTP Authentication Failure")
return False
if attachments:
for f in attachments:
name = os.path.basename(f)
with salt.utils.files.fopen(f, 'rb') as fin:
att = email.mime.application.MIMEApplication(fin.read(), Name=name)
att['Content-Disposition'] = 'attachment; filename="{0}"'.format(name)
msg.attach(att)
try:
smtpconn.sendmail(sender, recipients, msg.as_string())
except smtplib.SMTPRecipientsRefused:
log.debug("All recipients were refused.")
return False
except smtplib.SMTPHeloError:
log.debug("The server didn’t reply properly to the HELO greeting.")
return False
except smtplib.SMTPSenderRefused:
log.debug("The server didn’t accept the %s.", sender)
return False
except smtplib.SMTPDataError:
log.debug("The server replied with an unexpected error code.")
return False
smtpconn.quit()
return True | [
"def",
"send_msg",
"(",
"recipient",
",",
"message",
",",
"subject",
"=",
"'Message from Salt'",
",",
"sender",
"=",
"None",
",",
"server",
"=",
"None",
",",
"use_ssl",
"=",
"'True'",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"prof... | Send a message to an SMTP recipient. Designed for use in states.
CLI Examples:
.. code-block:: bash
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' profile='my-smtp-account'
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com'
salt '*' smtp.send_msg 'admin@example.com' 'This is a salt module test' username='myuser' password='verybadpass' sender='admin@example.com' server='smtp.domain.com' attachments="['/var/log/messages']" | [
"Send",
"a",
"message",
"to",
"an",
"SMTP",
"recipient",
".",
"Designed",
"for",
"use",
"in",
"states",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smtp.py#L77-L175 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | add_distinguished_name | def add_distinguished_name(list_name, item_name):
'''
Adds a distinguished name to a distinguished name list.
list_name(str): The name of the specific policy distinguished name list to append to.
item_name(str): The distinguished name to append.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_distinguished_names",
"params": [list_name, {"item_name": item_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | python | def add_distinguished_name(list_name, item_name):
'''
Adds a distinguished name to a distinguished name list.
list_name(str): The name of the specific policy distinguished name list to append to.
item_name(str): The distinguished name to append.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_distinguished_names",
"params": [list_name, {"item_name": item_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | [
"def",
"add_distinguished_name",
"(",
"list_name",
",",
"item_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_distinguished_names\"",
",",
"\"params\"",
":",
"[",
"list_name"... | Adds a distinguished name to a distinguished name list.
list_name(str): The name of the specific policy distinguished name list to append to.
item_name(str): The distinguished name to append.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name MyDistinguishedList cn=foo.bar.com | [
"Adds",
"a",
"distinguished",
"name",
"to",
"a",
"distinguished",
"name",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L76-L98 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | add_distinguished_name_list | def add_distinguished_name_list(list_name):
'''
Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_distinguished_names_list",
"params": [{"list_name": list_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | python | def add_distinguished_name_list(list_name):
'''
Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_distinguished_names_list",
"params": [{"list_name": list_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | [
"def",
"add_distinguished_name_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_distinguished_names_list\"",
",",
"\"params\"",
":",
"[",
"{",
"\"list_name\"",... | Add a list of policy distinguished names.
list_name(str): The name of the specific policy distinguished name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_distinguished_name_list MyDistinguishedList | [
"Add",
"a",
"list",
"of",
"policy",
"distinguished",
"names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L101-L121 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | add_domain_name | def add_domain_name(list_name, item_name):
'''
Adds a domain name to a domain name list.
list_name(str): The name of the specific policy domain name list to append to.
item_name(str): The domain name to append.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_domain_names",
"params": [list_name, {"item_name": item_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | python | def add_domain_name(list_name, item_name):
'''
Adds a domain name to a domain name list.
list_name(str): The name of the specific policy domain name list to append to.
item_name(str): The domain name to append.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_domain_names",
"params": [list_name, {"item_name": item_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | [
"def",
"add_domain_name",
"(",
"list_name",
",",
"item_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_domain_names\"",
",",
"\"params\"",
":",
"[",
"list_name",
",",
"{"... | Adds a domain name to a domain name list.
list_name(str): The name of the specific policy domain name list to append to.
item_name(str): The domain name to append.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_domain_name MyDomainName foo.bar.com | [
"Adds",
"a",
"domain",
"name",
"to",
"a",
"domain",
"name",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L124-L146 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | add_domain_name_list | def add_domain_name_list(list_name):
'''
Add a list of policy domain names.
list_name(str): The name of the specific policy domain name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_domain_names_list",
"params": [{"list_name": list_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | python | def add_domain_name_list(list_name):
'''
Add a list of policy domain names.
list_name(str): The name of the specific policy domain name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_domain_names_list",
"params": [{"list_name": list_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | [
"def",
"add_domain_name_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_domain_names_list\"",
",",
"\"params\"",
":",
"[",
"{",
"\"list_name\"",
":",
"lis... | Add a list of policy domain names.
list_name(str): The name of the specific policy domain name list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_domain_name_list MyDomainNameList | [
"Add",
"a",
"list",
"of",
"policy",
"domain",
"names",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L149-L169 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | add_ip_address | def add_ip_address(list_name, item_name):
'''
Add an IP address to an IP address list.
list_name(str): The name of the specific policy IP address list to append to.
item_name(str): The IP address to append to the list.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_ip_addresses",
"params": [list_name, {"item_name": item_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | python | def add_ip_address(list_name, item_name):
'''
Add an IP address to an IP address list.
list_name(str): The name of the specific policy IP address list to append to.
item_name(str): The IP address to append to the list.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_ip_addresses",
"params": [list_name, {"item_name": item_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | [
"def",
"add_ip_address",
"(",
"list_name",
",",
"item_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_ip_addresses\"",
",",
"\"params\"",
":",
"[",
"list_name",
",",
"{",... | Add an IP address to an IP address list.
list_name(str): The name of the specific policy IP address list to append to.
item_name(str): The IP address to append to the list.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_ip_address MyIPAddressList 10.0.0.0/24 | [
"Add",
"an",
"IP",
"address",
"to",
"an",
"IP",
"address",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L172-L194 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | add_ip_address_list | def add_ip_address_list(list_name):
'''
Retrieves a list of all IP address lists.
list_name(str): The name of the specific IP address list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_ip_addresses_list",
"params": [{"list_name": list_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | python | def add_ip_address_list(list_name):
'''
Retrieves a list of all IP address lists.
list_name(str): The name of the specific IP address list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "add_policy_ip_addresses_list",
"params": [{"list_name": list_name}]}
response = __proxy__['bluecoat_sslv.call'](payload, True)
return _validate_change_result(response) | [
"def",
"add_ip_address_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"add_policy_ip_addresses_list\"",
",",
"\"params\"",
":",
"[",
"{",
"\"list_name\"",
":",
"list... | Retrieves a list of all IP address lists.
list_name(str): The name of the specific IP address list to add.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.add_ip_address_list MyIPAddressList | [
"Retrieves",
"a",
"list",
"of",
"all",
"IP",
"address",
"lists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L197-L217 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | get_distinguished_name_list | def get_distinguished_name_list(list_name):
'''
Retrieves a specific policy distinguished name list.
list_name(str): The name of the specific policy distinguished name list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "get_policy_distinguished_names",
"params": [list_name, 0, 256]}
response = __proxy__['bluecoat_sslv.call'](payload, False)
return _convert_to_list(response, 'item_name') | python | def get_distinguished_name_list(list_name):
'''
Retrieves a specific policy distinguished name list.
list_name(str): The name of the specific policy distinguished name list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "get_policy_distinguished_names",
"params": [list_name, 0, 256]}
response = __proxy__['bluecoat_sslv.call'](payload, False)
return _convert_to_list(response, 'item_name') | [
"def",
"get_distinguished_name_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"get_policy_distinguished_names\"",
",",
"\"params\"",
":",
"[",
"list_name",
",",
"0",
... | Retrieves a specific policy distinguished name list.
list_name(str): The name of the specific policy distinguished name list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_distinguished_name_list MyDistinguishedList | [
"Retrieves",
"a",
"specific",
"policy",
"distinguished",
"name",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L220-L240 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | get_domain_list | def get_domain_list(list_name):
'''
Retrieves a specific policy domain name list.
list_name(str): The name of the specific policy domain name list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_domain_list MyDomainNameList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "get_policy_domain_names",
"params": [list_name, 0, 256]}
response = __proxy__['bluecoat_sslv.call'](payload, False)
return _convert_to_list(response, 'item_name') | python | def get_domain_list(list_name):
'''
Retrieves a specific policy domain name list.
list_name(str): The name of the specific policy domain name list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_domain_list MyDomainNameList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "get_policy_domain_names",
"params": [list_name, 0, 256]}
response = __proxy__['bluecoat_sslv.call'](payload, False)
return _convert_to_list(response, 'item_name') | [
"def",
"get_domain_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"get_policy_domain_names\"",
",",
"\"params\"",
":",
"[",
"list_name",
",",
"0",
",",
"256",
"]... | Retrieves a specific policy domain name list.
list_name(str): The name of the specific policy domain name list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_domain_list MyDomainNameList | [
"Retrieves",
"a",
"specific",
"policy",
"domain",
"name",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L264-L284 | train |
saltstack/salt | salt/modules/bluecoat_sslv.py | get_ip_address_list | def get_ip_address_list(list_name):
'''
Retrieves a specific IP address list.
list_name(str): The name of the specific policy IP address list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "get_policy_ip_addresses",
"params": [list_name, 0, 256]}
response = __proxy__['bluecoat_sslv.call'](payload, False)
return _convert_to_list(response, 'item_name') | python | def get_ip_address_list(list_name):
'''
Retrieves a specific IP address list.
list_name(str): The name of the specific policy IP address list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList
'''
payload = {"jsonrpc": "2.0",
"id": "ID0",
"method": "get_policy_ip_addresses",
"params": [list_name, 0, 256]}
response = __proxy__['bluecoat_sslv.call'](payload, False)
return _convert_to_list(response, 'item_name') | [
"def",
"get_ip_address_list",
"(",
"list_name",
")",
":",
"payload",
"=",
"{",
"\"jsonrpc\"",
":",
"\"2.0\"",
",",
"\"id\"",
":",
"\"ID0\"",
",",
"\"method\"",
":",
"\"get_policy_ip_addresses\"",
",",
"\"params\"",
":",
"[",
"list_name",
",",
"0",
",",
"256",
... | Retrieves a specific IP address list.
list_name(str): The name of the specific policy IP address list to retrieve.
CLI Example:
.. code-block:: bash
salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList | [
"Retrieves",
"a",
"specific",
"IP",
"address",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L308-L328 | train |
saltstack/salt | salt/utils/win_runas.py | runas | def runas(cmdLine, username, password=None, cwd=None):
'''
Run a command as another user. If the process is running as an admin or
system account this method does not require a password. Other non
privileged accounts need to provide a password for the user to runas.
Commands are run in with the highest level privileges possible for the
account provided.
'''
# Elevate the token from the current process
access = (
win32security.TOKEN_QUERY |
win32security.TOKEN_ADJUST_PRIVILEGES
)
th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access)
salt.platform.win.elevate_token(th)
# Try to impersonate the SYSTEM user. This process needs to be running as a
# user who as been granted the SeImpersonatePrivilege, Administrator
# accounts have this permission by default.
try:
impersonation_token = salt.platform.win.impersonate_sid(
salt.platform.win.SYSTEM_SID,
session_id=0,
privs=['SeTcbPrivilege'],
)
except WindowsError: # pylint: disable=undefined-variable
log.debug("Unable to impersonate SYSTEM user")
impersonation_token = None
# Impersonation of the SYSTEM user failed. Fallback to an un-privileged
# runas.
if not impersonation_token:
log.debug("No impersonation token, using unprivileged runas")
return runas_unpriv(cmdLine, username, password, cwd)
username, domain = split_username(username)
# Validate the domain and sid exist for the username
try:
_, domain, _ = win32security.LookupAccountName(domain, username)
except pywintypes.error as exc:
message = win32api.FormatMessage(exc.winerror).rstrip('\n')
raise CommandExecutionError(message)
if domain == 'NT AUTHORITY':
# Logon as a system level account, SYSTEM, LOCAL SERVICE, or NETWORK
# SERVICE.
logonType = win32con.LOGON32_LOGON_SERVICE
user_token = win32security.LogonUser(
username,
domain,
'',
win32con.LOGON32_LOGON_SERVICE,
win32con.LOGON32_PROVIDER_DEFAULT,
)
elif password:
# Login with a password.
user_token = win32security.LogonUser(
username,
domain,
password,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT,
)
else:
# Login without a password. This always returns an elevated token.
user_token = salt.platform.win.logon_msv1_s4u(username).Token
# Get a linked user token to elevate if needed
elevation_type = win32security.GetTokenInformation(
user_token, win32security.TokenElevationType
)
if elevation_type > 1:
user_token = win32security.GetTokenInformation(
user_token,
win32security.TokenLinkedToken
)
# Elevate the user token
salt.platform.win.elevate_token(user_token)
# Make sure the user's token has access to a windows station and desktop
salt.platform.win.grant_winsta_and_desktop(user_token)
# Create pipes for standard in, out and error streams
security_attributes = win32security.SECURITY_ATTRIBUTES()
security_attributes.bInheritHandle = 1
stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0)
stdin_read = salt.platform.win.make_inheritable(stdin_read)
stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0)
stdout_write = salt.platform.win.make_inheritable(stdout_write)
stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0)
stderr_write = salt.platform.win.make_inheritable(stderr_write)
# Run the process without showing a window.
creationflags = (
win32process.CREATE_NO_WINDOW |
win32process.CREATE_NEW_CONSOLE |
win32process.CREATE_SUSPENDED
)
startup_info = salt.platform.win.STARTUPINFO(
dwFlags=win32con.STARTF_USESTDHANDLES,
hStdInput=stdin_read.handle,
hStdOutput=stdout_write.handle,
hStdError=stderr_write.handle,
)
# Create the environment for the user
env = win32profile.CreateEnvironmentBlock(user_token, False)
# Start the process in a suspended state.
process_info = salt.platform.win.CreateProcessWithTokenW(
int(user_token),
logonflags=1,
applicationname=None,
commandline=cmdLine,
currentdirectory=cwd,
creationflags=creationflags,
startupinfo=startup_info,
environment=env,
)
hProcess = process_info.hProcess
hThread = process_info.hThread
dwProcessId = process_info.dwProcessId
dwThreadId = process_info.dwThreadId
salt.platform.win.kernel32.CloseHandle(stdin_write.handle)
salt.platform.win.kernel32.CloseHandle(stdout_write.handle)
salt.platform.win.kernel32.CloseHandle(stderr_write.handle)
ret = {'pid': dwProcessId}
# Resume the process
psutil.Process(dwProcessId).resume()
# Wait for the process to exit and get it's return code.
if win32event.WaitForSingleObject(hProcess, win32event.INFINITE) == win32con.WAIT_OBJECT_0:
exitcode = win32process.GetExitCodeProcess(hProcess)
ret['retcode'] = exitcode
# Read standard out
fd_out = msvcrt.open_osfhandle(stdout_read.handle, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_out, 'r') as f_out:
stdout = f_out.read()
ret['stdout'] = stdout
# Read standard error
fd_err = msvcrt.open_osfhandle(stderr_read.handle, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_err, 'r') as f_err:
stderr = f_err.read()
ret['stderr'] = stderr
salt.platform.win.kernel32.CloseHandle(hProcess)
win32api.CloseHandle(user_token)
if impersonation_token:
win32security.RevertToSelf()
win32api.CloseHandle(impersonation_token)
return ret | python | def runas(cmdLine, username, password=None, cwd=None):
'''
Run a command as another user. If the process is running as an admin or
system account this method does not require a password. Other non
privileged accounts need to provide a password for the user to runas.
Commands are run in with the highest level privileges possible for the
account provided.
'''
# Elevate the token from the current process
access = (
win32security.TOKEN_QUERY |
win32security.TOKEN_ADJUST_PRIVILEGES
)
th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), access)
salt.platform.win.elevate_token(th)
# Try to impersonate the SYSTEM user. This process needs to be running as a
# user who as been granted the SeImpersonatePrivilege, Administrator
# accounts have this permission by default.
try:
impersonation_token = salt.platform.win.impersonate_sid(
salt.platform.win.SYSTEM_SID,
session_id=0,
privs=['SeTcbPrivilege'],
)
except WindowsError: # pylint: disable=undefined-variable
log.debug("Unable to impersonate SYSTEM user")
impersonation_token = None
# Impersonation of the SYSTEM user failed. Fallback to an un-privileged
# runas.
if not impersonation_token:
log.debug("No impersonation token, using unprivileged runas")
return runas_unpriv(cmdLine, username, password, cwd)
username, domain = split_username(username)
# Validate the domain and sid exist for the username
try:
_, domain, _ = win32security.LookupAccountName(domain, username)
except pywintypes.error as exc:
message = win32api.FormatMessage(exc.winerror).rstrip('\n')
raise CommandExecutionError(message)
if domain == 'NT AUTHORITY':
# Logon as a system level account, SYSTEM, LOCAL SERVICE, or NETWORK
# SERVICE.
logonType = win32con.LOGON32_LOGON_SERVICE
user_token = win32security.LogonUser(
username,
domain,
'',
win32con.LOGON32_LOGON_SERVICE,
win32con.LOGON32_PROVIDER_DEFAULT,
)
elif password:
# Login with a password.
user_token = win32security.LogonUser(
username,
domain,
password,
win32con.LOGON32_LOGON_INTERACTIVE,
win32con.LOGON32_PROVIDER_DEFAULT,
)
else:
# Login without a password. This always returns an elevated token.
user_token = salt.platform.win.logon_msv1_s4u(username).Token
# Get a linked user token to elevate if needed
elevation_type = win32security.GetTokenInformation(
user_token, win32security.TokenElevationType
)
if elevation_type > 1:
user_token = win32security.GetTokenInformation(
user_token,
win32security.TokenLinkedToken
)
# Elevate the user token
salt.platform.win.elevate_token(user_token)
# Make sure the user's token has access to a windows station and desktop
salt.platform.win.grant_winsta_and_desktop(user_token)
# Create pipes for standard in, out and error streams
security_attributes = win32security.SECURITY_ATTRIBUTES()
security_attributes.bInheritHandle = 1
stdin_read, stdin_write = win32pipe.CreatePipe(security_attributes, 0)
stdin_read = salt.platform.win.make_inheritable(stdin_read)
stdout_read, stdout_write = win32pipe.CreatePipe(security_attributes, 0)
stdout_write = salt.platform.win.make_inheritable(stdout_write)
stderr_read, stderr_write = win32pipe.CreatePipe(security_attributes, 0)
stderr_write = salt.platform.win.make_inheritable(stderr_write)
# Run the process without showing a window.
creationflags = (
win32process.CREATE_NO_WINDOW |
win32process.CREATE_NEW_CONSOLE |
win32process.CREATE_SUSPENDED
)
startup_info = salt.platform.win.STARTUPINFO(
dwFlags=win32con.STARTF_USESTDHANDLES,
hStdInput=stdin_read.handle,
hStdOutput=stdout_write.handle,
hStdError=stderr_write.handle,
)
# Create the environment for the user
env = win32profile.CreateEnvironmentBlock(user_token, False)
# Start the process in a suspended state.
process_info = salt.platform.win.CreateProcessWithTokenW(
int(user_token),
logonflags=1,
applicationname=None,
commandline=cmdLine,
currentdirectory=cwd,
creationflags=creationflags,
startupinfo=startup_info,
environment=env,
)
hProcess = process_info.hProcess
hThread = process_info.hThread
dwProcessId = process_info.dwProcessId
dwThreadId = process_info.dwThreadId
salt.platform.win.kernel32.CloseHandle(stdin_write.handle)
salt.platform.win.kernel32.CloseHandle(stdout_write.handle)
salt.platform.win.kernel32.CloseHandle(stderr_write.handle)
ret = {'pid': dwProcessId}
# Resume the process
psutil.Process(dwProcessId).resume()
# Wait for the process to exit and get it's return code.
if win32event.WaitForSingleObject(hProcess, win32event.INFINITE) == win32con.WAIT_OBJECT_0:
exitcode = win32process.GetExitCodeProcess(hProcess)
ret['retcode'] = exitcode
# Read standard out
fd_out = msvcrt.open_osfhandle(stdout_read.handle, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_out, 'r') as f_out:
stdout = f_out.read()
ret['stdout'] = stdout
# Read standard error
fd_err = msvcrt.open_osfhandle(stderr_read.handle, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_err, 'r') as f_err:
stderr = f_err.read()
ret['stderr'] = stderr
salt.platform.win.kernel32.CloseHandle(hProcess)
win32api.CloseHandle(user_token)
if impersonation_token:
win32security.RevertToSelf()
win32api.CloseHandle(impersonation_token)
return ret | [
"def",
"runas",
"(",
"cmdLine",
",",
"username",
",",
"password",
"=",
"None",
",",
"cwd",
"=",
"None",
")",
":",
"# Elevate the token from the current process",
"access",
"=",
"(",
"win32security",
".",
"TOKEN_QUERY",
"|",
"win32security",
".",
"TOKEN_ADJUST_PRIV... | Run a command as another user. If the process is running as an admin or
system account this method does not require a password. Other non
privileged accounts need to provide a password for the user to runas.
Commands are run in with the highest level privileges possible for the
account provided. | [
"Run",
"a",
"command",
"as",
"another",
"user",
".",
"If",
"the",
"process",
"is",
"running",
"as",
"an",
"admin",
"or",
"system",
"account",
"this",
"method",
"does",
"not",
"require",
"a",
"password",
".",
"Other",
"non",
"privileged",
"accounts",
"need"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_runas.py#L62-L224 | train |
saltstack/salt | salt/utils/win_runas.py | runas_unpriv | def runas_unpriv(cmd, username, password, cwd=None):
'''
Runas that works for non-priviledged users
'''
# Create a pipe to set as stdout in the child. The write handle needs to be
# inheritable.
c2pread, c2pwrite = salt.platform.win.CreatePipe(
inherit_read=False, inherit_write=True,
)
errread, errwrite = salt.platform.win.CreatePipe(
inherit_read=False, inherit_write=True,
)
# Create inheritable copy of the stdin
stdin = salt.platform.win.kernel32.GetStdHandle(
salt.platform.win.STD_INPUT_HANDLE,
)
dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True)
# Get startup info structure
startup_info = salt.platform.win.STARTUPINFO(
dwFlags=win32con.STARTF_USESTDHANDLES,
hStdInput=dupin,
hStdOutput=c2pwrite,
hStdError=errwrite,
)
username, domain = split_username(username)
# Run command and return process info structure
process_info = salt.platform.win.CreateProcessWithLogonW(
username=username,
domain=domain,
password=password,
logonflags=salt.platform.win.LOGON_WITH_PROFILE,
commandline=cmd,
startupinfo=startup_info,
currentdirectory=cwd)
salt.platform.win.kernel32.CloseHandle(dupin)
salt.platform.win.kernel32.CloseHandle(c2pwrite)
salt.platform.win.kernel32.CloseHandle(errwrite)
salt.platform.win.kernel32.CloseHandle(process_info.hThread)
# Initialize ret and set first element
ret = {'pid': process_info.dwProcessId}
# Get Standard Out
fd_out = msvcrt.open_osfhandle(c2pread, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_out, 'r') as f_out:
ret['stdout'] = f_out.read()
# Get Standard Error
fd_err = msvcrt.open_osfhandle(errread, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_err, 'r') as f_err:
ret['stderr'] = f_err.read()
# Get Return Code
if salt.platform.win.kernel32.WaitForSingleObject(process_info.hProcess, win32event.INFINITE) == \
win32con.WAIT_OBJECT_0:
exitcode = salt.platform.win.wintypes.DWORD()
salt.platform.win.kernel32.GetExitCodeProcess(process_info.hProcess,
ctypes.byref(exitcode))
ret['retcode'] = exitcode.value
# Close handle to process
salt.platform.win.kernel32.CloseHandle(process_info.hProcess)
return ret | python | def runas_unpriv(cmd, username, password, cwd=None):
'''
Runas that works for non-priviledged users
'''
# Create a pipe to set as stdout in the child. The write handle needs to be
# inheritable.
c2pread, c2pwrite = salt.platform.win.CreatePipe(
inherit_read=False, inherit_write=True,
)
errread, errwrite = salt.platform.win.CreatePipe(
inherit_read=False, inherit_write=True,
)
# Create inheritable copy of the stdin
stdin = salt.platform.win.kernel32.GetStdHandle(
salt.platform.win.STD_INPUT_HANDLE,
)
dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True)
# Get startup info structure
startup_info = salt.platform.win.STARTUPINFO(
dwFlags=win32con.STARTF_USESTDHANDLES,
hStdInput=dupin,
hStdOutput=c2pwrite,
hStdError=errwrite,
)
username, domain = split_username(username)
# Run command and return process info structure
process_info = salt.platform.win.CreateProcessWithLogonW(
username=username,
domain=domain,
password=password,
logonflags=salt.platform.win.LOGON_WITH_PROFILE,
commandline=cmd,
startupinfo=startup_info,
currentdirectory=cwd)
salt.platform.win.kernel32.CloseHandle(dupin)
salt.platform.win.kernel32.CloseHandle(c2pwrite)
salt.platform.win.kernel32.CloseHandle(errwrite)
salt.platform.win.kernel32.CloseHandle(process_info.hThread)
# Initialize ret and set first element
ret = {'pid': process_info.dwProcessId}
# Get Standard Out
fd_out = msvcrt.open_osfhandle(c2pread, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_out, 'r') as f_out:
ret['stdout'] = f_out.read()
# Get Standard Error
fd_err = msvcrt.open_osfhandle(errread, os.O_RDONLY | os.O_TEXT)
with os.fdopen(fd_err, 'r') as f_err:
ret['stderr'] = f_err.read()
# Get Return Code
if salt.platform.win.kernel32.WaitForSingleObject(process_info.hProcess, win32event.INFINITE) == \
win32con.WAIT_OBJECT_0:
exitcode = salt.platform.win.wintypes.DWORD()
salt.platform.win.kernel32.GetExitCodeProcess(process_info.hProcess,
ctypes.byref(exitcode))
ret['retcode'] = exitcode.value
# Close handle to process
salt.platform.win.kernel32.CloseHandle(process_info.hProcess)
return ret | [
"def",
"runas_unpriv",
"(",
"cmd",
",",
"username",
",",
"password",
",",
"cwd",
"=",
"None",
")",
":",
"# Create a pipe to set as stdout in the child. The write handle needs to be",
"# inheritable.",
"c2pread",
",",
"c2pwrite",
"=",
"salt",
".",
"platform",
".",
"win... | Runas that works for non-priviledged users | [
"Runas",
"that",
"works",
"for",
"non",
"-",
"priviledged",
"users"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_runas.py#L227-L295 | train |
saltstack/salt | salt/matchers/data_match.py | match | def match(tgt, functions=None, opts=None):
'''
Match based on the local data store on the minion
'''
if not opts:
opts = __opts__
if functions is None:
utils = salt.loader.utils(opts)
functions = salt.loader.minion_mods(opts, utils=utils)
comps = tgt.split(':')
if len(comps) < 2:
return False
val = functions['data.getval'](comps[0])
if val is None:
# The value is not defined
return False
if isinstance(val, list):
# We are matching a single component to a single list member
for member in val:
if fnmatch.fnmatch(six.text_type(member).lower(), comps[1].lower()):
return True
return False
if isinstance(val, dict):
if comps[1] in val:
return True
return False
return bool(fnmatch.fnmatch(
val,
comps[1],
)) | python | def match(tgt, functions=None, opts=None):
'''
Match based on the local data store on the minion
'''
if not opts:
opts = __opts__
if functions is None:
utils = salt.loader.utils(opts)
functions = salt.loader.minion_mods(opts, utils=utils)
comps = tgt.split(':')
if len(comps) < 2:
return False
val = functions['data.getval'](comps[0])
if val is None:
# The value is not defined
return False
if isinstance(val, list):
# We are matching a single component to a single list member
for member in val:
if fnmatch.fnmatch(six.text_type(member).lower(), comps[1].lower()):
return True
return False
if isinstance(val, dict):
if comps[1] in val:
return True
return False
return bool(fnmatch.fnmatch(
val,
comps[1],
)) | [
"def",
"match",
"(",
"tgt",
",",
"functions",
"=",
"None",
",",
"opts",
"=",
"None",
")",
":",
"if",
"not",
"opts",
":",
"opts",
"=",
"__opts__",
"if",
"functions",
"is",
"None",
":",
"utils",
"=",
"salt",
".",
"loader",
".",
"utils",
"(",
"opts",
... | Match based on the local data store on the minion | [
"Match",
"based",
"on",
"the",
"local",
"data",
"store",
"on",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/data_match.py#L19-L48 | train |
saltstack/salt | salt/states/glance.py | _find_image | def _find_image(name):
'''
Tries to find image with given name, returns
- image, 'Found image <name>'
- None, 'No such image found'
- False, 'Found more than one image with given name'
'''
try:
images = __salt__['glance.image_list'](name=name)
except kstone_Unauthorized:
return False, 'keystoneclient: Unauthorized'
except glance_Unauthorized:
return False, 'glanceclient: Unauthorized'
log.debug('Got images: %s', images)
if type(images) is dict and len(images) == 1 and 'images' in images:
images = images['images']
images_list = images.values() if type(images) is dict else images
if not images_list:
return None, 'No image with name "{0}"'.format(name)
elif len(images_list) == 1:
return images_list[0], 'Found image {0}'.format(name)
elif len(images_list) > 1:
return False, 'Found more than one image with given name'
else:
raise NotImplementedError | python | def _find_image(name):
'''
Tries to find image with given name, returns
- image, 'Found image <name>'
- None, 'No such image found'
- False, 'Found more than one image with given name'
'''
try:
images = __salt__['glance.image_list'](name=name)
except kstone_Unauthorized:
return False, 'keystoneclient: Unauthorized'
except glance_Unauthorized:
return False, 'glanceclient: Unauthorized'
log.debug('Got images: %s', images)
if type(images) is dict and len(images) == 1 and 'images' in images:
images = images['images']
images_list = images.values() if type(images) is dict else images
if not images_list:
return None, 'No image with name "{0}"'.format(name)
elif len(images_list) == 1:
return images_list[0], 'Found image {0}'.format(name)
elif len(images_list) > 1:
return False, 'Found more than one image with given name'
else:
raise NotImplementedError | [
"def",
"_find_image",
"(",
"name",
")",
":",
"try",
":",
"images",
"=",
"__salt__",
"[",
"'glance.image_list'",
"]",
"(",
"name",
"=",
"name",
")",
"except",
"kstone_Unauthorized",
":",
"return",
"False",
",",
"'keystoneclient: Unauthorized'",
"except",
"glance_... | Tries to find image with given name, returns
- image, 'Found image <name>'
- None, 'No such image found'
- False, 'Found more than one image with given name' | [
"Tries",
"to",
"find",
"image",
"with",
"given",
"name",
"returns",
"-",
"image",
"Found",
"image",
"<name",
">",
"-",
"None",
"No",
"such",
"image",
"found",
"-",
"False",
"Found",
"more",
"than",
"one",
"image",
"with",
"given",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glance.py#L43-L70 | train |
saltstack/salt | salt/states/glance.py | image_present | def image_present(name, visibility='public', protected=None,
checksum=None, location=None, disk_format='raw', wait_for=None,
timeout=30):
'''
Checks if given image is present with properties
set as specified.
An image should got through the stages 'queued', 'saving'
before becoming 'active'. The attribute 'checksum' can
only be checked once the image is active.
If you don't specify 'wait_for' but 'checksum' the function
will wait for the image to become active before comparing
checksums. If you don't specify checksum either the function
will return when the image reached 'saving'.
The default timeout for both is 30 seconds.
Supported properties:
- visibility ('public' or 'private')
- protected (bool)
- checksum (string, md5sum)
- location (URL, to copy from)
- disk_format ('raw' (default), 'vhd', 'vhdx', 'vmdk', 'vdi', 'iso',
'qcow2', 'aki', 'ari' or 'ami')
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': '',
}
acceptable = ['queued', 'saving', 'active']
if wait_for is None and checksum is None:
wait_for = 'saving'
elif wait_for is None and checksum is not None:
wait_for = 'active'
# Just pop states until we reach the
# first acceptable one:
while len(acceptable) > 1:
if acceptable[0] == wait_for:
break
else:
acceptable.pop(0)
image, msg = _find_image(name)
if image is False:
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = False
ret['comment'] = msg
return ret
log.debug(msg)
# No image yet and we know where to get one
if image is None and location is not None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'glance.image_present would ' \
'create an image from {0}'.format(location)
return ret
image = __salt__['glance.image_create'](name=name,
protected=protected, visibility=visibility,
location=location, disk_format=disk_format)
log.debug('Created new image:\n%s', image)
ret['changes'] = {
name:
{
'new':
{
'id': image['id']
},
'old': None
}
}
timer = timeout
# Kinda busy-loopy but I don't think the Glance
# API has events we can listen for
while timer > 0:
if 'status' in image and \
image['status'] in acceptable:
log.debug('Image %s has reached status %s',
image['name'], image['status'])
break
else:
timer -= 5
time.sleep(5)
image, msg = _find_image(name)
if not image:
ret['result'] = False
ret['comment'] += 'Created image {0} '.format(
name) + ' vanished:\n' + msg
return ret
if timer <= 0 and image['status'] not in acceptable:
ret['result'] = False
ret['comment'] += 'Image didn\'t reach an acceptable '+\
'state ({0}) before timeout:\n'.format(acceptable)+\
'\tLast status was "{0}".\n'.format(image['status'])
# There's no image but where would I get one??
elif location is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'No location to copy image from specified,\n' +\
'glance.image_present would not create one'
else:
ret['result'] = False
ret['comment'] = 'No location to copy image from specified,\n' +\
'not creating a new image.'
return ret
# If we've created a new image also return its last status:
if name in ret['changes']:
ret['changes'][name]['new']['status'] = image['status']
if visibility:
if image['visibility'] != visibility:
old_value = image['visibility']
if not __opts__['test']:
image = __salt__['glance.image_update'](
id=image['id'], visibility=visibility)
# Check if image_update() worked:
if image['visibility'] != visibility:
if not __opts__['test']:
ret['result'] = False
elif __opts__['test']:
ret['result'] = None
ret['comment'] += '"visibility" is {0}, '\
'should be {1}.\n'.format(image['visibility'],
visibility)
else:
if 'new' in ret['changes']:
ret['changes']['new']['visibility'] = visibility
else:
ret['changes']['new'] = {'visibility': visibility}
if 'old' in ret['changes']:
ret['changes']['old']['visibility'] = old_value
else:
ret['changes']['old'] = {'visibility': old_value}
else:
ret['comment'] += '"visibility" is correct ({0}).\n'.format(
visibility)
if protected is not None:
if not isinstance(protected, bool) or image['protected'] ^ protected:
if not __opts__['test']:
ret['result'] = False
else:
ret['result'] = None
ret['comment'] += '"protected" is {0}, should be {1}.\n'.format(
image['protected'], protected)
else:
ret['comment'] += '"protected" is correct ({0}).\n'.format(
protected)
if 'status' in image and checksum:
if image['status'] == 'active':
if 'checksum' not in image:
# Refresh our info about the image
image = __salt__['glance.image_show'](image['id'])
if 'checksum' not in image:
if not __opts__['test']:
ret['result'] = False
else:
ret['result'] = None
ret['comment'] += 'No checksum available for this image:\n' +\
'\tImage has status "{0}".'.format(image['status'])
elif image['checksum'] != checksum:
if not __opts__['test']:
ret['result'] = False
else:
ret['result'] = None
ret['comment'] += '"checksum" is {0}, should be {1}.\n'.format(
image['checksum'], checksum)
else:
ret['comment'] += '"checksum" is correct ({0}).\n'.format(
checksum)
elif image['status'] in ['saving', 'queued']:
ret['comment'] += 'Checksum won\'t be verified as image ' +\
'hasn\'t reached\n\t "status=active" yet.\n'
log.debug('glance.image_present will return: %s', ret)
return ret | python | def image_present(name, visibility='public', protected=None,
checksum=None, location=None, disk_format='raw', wait_for=None,
timeout=30):
'''
Checks if given image is present with properties
set as specified.
An image should got through the stages 'queued', 'saving'
before becoming 'active'. The attribute 'checksum' can
only be checked once the image is active.
If you don't specify 'wait_for' but 'checksum' the function
will wait for the image to become active before comparing
checksums. If you don't specify checksum either the function
will return when the image reached 'saving'.
The default timeout for both is 30 seconds.
Supported properties:
- visibility ('public' or 'private')
- protected (bool)
- checksum (string, md5sum)
- location (URL, to copy from)
- disk_format ('raw' (default), 'vhd', 'vhdx', 'vmdk', 'vdi', 'iso',
'qcow2', 'aki', 'ari' or 'ami')
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': '',
}
acceptable = ['queued', 'saving', 'active']
if wait_for is None and checksum is None:
wait_for = 'saving'
elif wait_for is None and checksum is not None:
wait_for = 'active'
# Just pop states until we reach the
# first acceptable one:
while len(acceptable) > 1:
if acceptable[0] == wait_for:
break
else:
acceptable.pop(0)
image, msg = _find_image(name)
if image is False:
if __opts__['test']:
ret['result'] = None
else:
ret['result'] = False
ret['comment'] = msg
return ret
log.debug(msg)
# No image yet and we know where to get one
if image is None and location is not None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'glance.image_present would ' \
'create an image from {0}'.format(location)
return ret
image = __salt__['glance.image_create'](name=name,
protected=protected, visibility=visibility,
location=location, disk_format=disk_format)
log.debug('Created new image:\n%s', image)
ret['changes'] = {
name:
{
'new':
{
'id': image['id']
},
'old': None
}
}
timer = timeout
# Kinda busy-loopy but I don't think the Glance
# API has events we can listen for
while timer > 0:
if 'status' in image and \
image['status'] in acceptable:
log.debug('Image %s has reached status %s',
image['name'], image['status'])
break
else:
timer -= 5
time.sleep(5)
image, msg = _find_image(name)
if not image:
ret['result'] = False
ret['comment'] += 'Created image {0} '.format(
name) + ' vanished:\n' + msg
return ret
if timer <= 0 and image['status'] not in acceptable:
ret['result'] = False
ret['comment'] += 'Image didn\'t reach an acceptable '+\
'state ({0}) before timeout:\n'.format(acceptable)+\
'\tLast status was "{0}".\n'.format(image['status'])
# There's no image but where would I get one??
elif location is None:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'No location to copy image from specified,\n' +\
'glance.image_present would not create one'
else:
ret['result'] = False
ret['comment'] = 'No location to copy image from specified,\n' +\
'not creating a new image.'
return ret
# If we've created a new image also return its last status:
if name in ret['changes']:
ret['changes'][name]['new']['status'] = image['status']
if visibility:
if image['visibility'] != visibility:
old_value = image['visibility']
if not __opts__['test']:
image = __salt__['glance.image_update'](
id=image['id'], visibility=visibility)
# Check if image_update() worked:
if image['visibility'] != visibility:
if not __opts__['test']:
ret['result'] = False
elif __opts__['test']:
ret['result'] = None
ret['comment'] += '"visibility" is {0}, '\
'should be {1}.\n'.format(image['visibility'],
visibility)
else:
if 'new' in ret['changes']:
ret['changes']['new']['visibility'] = visibility
else:
ret['changes']['new'] = {'visibility': visibility}
if 'old' in ret['changes']:
ret['changes']['old']['visibility'] = old_value
else:
ret['changes']['old'] = {'visibility': old_value}
else:
ret['comment'] += '"visibility" is correct ({0}).\n'.format(
visibility)
if protected is not None:
if not isinstance(protected, bool) or image['protected'] ^ protected:
if not __opts__['test']:
ret['result'] = False
else:
ret['result'] = None
ret['comment'] += '"protected" is {0}, should be {1}.\n'.format(
image['protected'], protected)
else:
ret['comment'] += '"protected" is correct ({0}).\n'.format(
protected)
if 'status' in image and checksum:
if image['status'] == 'active':
if 'checksum' not in image:
# Refresh our info about the image
image = __salt__['glance.image_show'](image['id'])
if 'checksum' not in image:
if not __opts__['test']:
ret['result'] = False
else:
ret['result'] = None
ret['comment'] += 'No checksum available for this image:\n' +\
'\tImage has status "{0}".'.format(image['status'])
elif image['checksum'] != checksum:
if not __opts__['test']:
ret['result'] = False
else:
ret['result'] = None
ret['comment'] += '"checksum" is {0}, should be {1}.\n'.format(
image['checksum'], checksum)
else:
ret['comment'] += '"checksum" is correct ({0}).\n'.format(
checksum)
elif image['status'] in ['saving', 'queued']:
ret['comment'] += 'Checksum won\'t be verified as image ' +\
'hasn\'t reached\n\t "status=active" yet.\n'
log.debug('glance.image_present will return: %s', ret)
return ret | [
"def",
"image_present",
"(",
"name",
",",
"visibility",
"=",
"'public'",
",",
"protected",
"=",
"None",
",",
"checksum",
"=",
"None",
",",
"location",
"=",
"None",
",",
"disk_format",
"=",
"'raw'",
",",
"wait_for",
"=",
"None",
",",
"timeout",
"=",
"30",... | Checks if given image is present with properties
set as specified.
An image should got through the stages 'queued', 'saving'
before becoming 'active'. The attribute 'checksum' can
only be checked once the image is active.
If you don't specify 'wait_for' but 'checksum' the function
will wait for the image to become active before comparing
checksums. If you don't specify checksum either the function
will return when the image reached 'saving'.
The default timeout for both is 30 seconds.
Supported properties:
- visibility ('public' or 'private')
- protected (bool)
- checksum (string, md5sum)
- location (URL, to copy from)
- disk_format ('raw' (default), 'vhd', 'vhdx', 'vmdk', 'vdi', 'iso',
'qcow2', 'aki', 'ari' or 'ami') | [
"Checks",
"if",
"given",
"image",
"is",
"present",
"with",
"properties",
"set",
"as",
"specified",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/glance.py#L73-L250 | train |
saltstack/salt | salt/returners/cassandra_cql_return.py | returner | def returner(ret):
'''
Return data to one of potentially many clustered cassandra nodes
'''
query = '''INSERT INTO {keyspace}.salt_returns (
jid, minion_id, fun, alter_time, full_ret, return, success
) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace())
statement_arguments = ['{0}'.format(ret['jid']),
'{0}'.format(ret['id']),
'{0}'.format(ret['fun']),
int(time.time() * 1000),
salt.utils.json.dumps(ret).replace("'", "''"),
salt.utils.json.dumps(ret['return']).replace("'", "''"),
ret.get('success', False)]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query,
'returner_return',
tuple(statement_arguments),
asynchronous=True)
except CommandExecutionError:
log.critical('Could not insert into salt_returns with Cassandra returner.')
raise
except Exception as e:
log.critical('Unexpected error while inserting into salt_returns: %s', e)
raise
# Store the last function called by the minion
# The data in salt.minions will be used by get_fun and get_minions
query = '''INSERT INTO {keyspace}.minions (
minion_id, last_fun
) VALUES (?, ?)'''.format(keyspace=_get_keyspace())
statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query,
'returner_minion',
tuple(statement_arguments),
asynchronous=True)
except CommandExecutionError:
log.critical('Could not store minion ID with Cassandra returner.')
raise
except Exception as e:
log.critical(
'Unexpected error while inserting minion ID into the minions '
'table: %s', e
)
raise | python | def returner(ret):
'''
Return data to one of potentially many clustered cassandra nodes
'''
query = '''INSERT INTO {keyspace}.salt_returns (
jid, minion_id, fun, alter_time, full_ret, return, success
) VALUES (?, ?, ?, ?, ?, ?, ?)'''.format(keyspace=_get_keyspace())
statement_arguments = ['{0}'.format(ret['jid']),
'{0}'.format(ret['id']),
'{0}'.format(ret['fun']),
int(time.time() * 1000),
salt.utils.json.dumps(ret).replace("'", "''"),
salt.utils.json.dumps(ret['return']).replace("'", "''"),
ret.get('success', False)]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query,
'returner_return',
tuple(statement_arguments),
asynchronous=True)
except CommandExecutionError:
log.critical('Could not insert into salt_returns with Cassandra returner.')
raise
except Exception as e:
log.critical('Unexpected error while inserting into salt_returns: %s', e)
raise
# Store the last function called by the minion
# The data in salt.minions will be used by get_fun and get_minions
query = '''INSERT INTO {keyspace}.minions (
minion_id, last_fun
) VALUES (?, ?)'''.format(keyspace=_get_keyspace())
statement_arguments = ['{0}'.format(ret['id']), '{0}'.format(ret['fun'])]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query,
'returner_minion',
tuple(statement_arguments),
asynchronous=True)
except CommandExecutionError:
log.critical('Could not store minion ID with Cassandra returner.')
raise
except Exception as e:
log.critical(
'Unexpected error while inserting minion ID into the minions '
'table: %s', e
)
raise | [
"def",
"returner",
"(",
"ret",
")",
":",
"query",
"=",
"'''INSERT INTO {keyspace}.salt_returns (\n jid, minion_id, fun, alter_time, full_ret, return, success\n ) VALUES (?, ?, ?, ?, ?, ?, ?)'''",
".",
"format",
"(",
"keyspace",
"=",
"_get_keyspace",
"(",
... | Return data to one of potentially many clustered cassandra nodes | [
"Return",
"data",
"to",
"one",
"of",
"potentially",
"many",
"clustered",
"cassandra",
"nodes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L192-L243 | train |
saltstack/salt | salt/returners/cassandra_cql_return.py | event_return | def event_return(events):
'''
Return event to one of potentially many clustered cassandra nodes
Requires that configuration be enabled via 'event_return'
option in master config.
Cassandra does not support an auto-increment feature due to the
highly inefficient nature of creating a monotonically increasing
number across all nodes in a distributed database. Each event
will be assigned a uuid by the connecting client.
'''
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
query = '''INSERT INTO {keyspace}.salt_events (
id, alter_time, data, master_id, tag
) VALUES (
?, ?, ?, ?, ?)
'''.format(keyspace=_get_keyspace())
statement_arguments = [six.text_type(uuid.uuid1()),
int(time.time() * 1000),
salt.utils.json.dumps(data).replace("'", "''"),
__opts__['id'],
tag]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events',
statement_arguments,
asynchronous=True)
except CommandExecutionError:
log.critical('Could not store events with Cassandra returner.')
raise
except Exception as e:
log.critical(
'Unexpected error while inserting into salt_events: %s', e)
raise | python | def event_return(events):
'''
Return event to one of potentially many clustered cassandra nodes
Requires that configuration be enabled via 'event_return'
option in master config.
Cassandra does not support an auto-increment feature due to the
highly inefficient nature of creating a monotonically increasing
number across all nodes in a distributed database. Each event
will be assigned a uuid by the connecting client.
'''
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
query = '''INSERT INTO {keyspace}.salt_events (
id, alter_time, data, master_id, tag
) VALUES (
?, ?, ?, ?, ?)
'''.format(keyspace=_get_keyspace())
statement_arguments = [six.text_type(uuid.uuid1()),
int(time.time() * 1000),
salt.utils.json.dumps(data).replace("'", "''"),
__opts__['id'],
tag]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query, 'salt_events',
statement_arguments,
asynchronous=True)
except CommandExecutionError:
log.critical('Could not store events with Cassandra returner.')
raise
except Exception as e:
log.critical(
'Unexpected error while inserting into salt_events: %s', e)
raise | [
"def",
"event_return",
"(",
"events",
")",
":",
"for",
"event",
"in",
"events",
":",
"tag",
"=",
"event",
".",
"get",
"(",
"'tag'",
",",
"''",
")",
"data",
"=",
"event",
".",
"get",
"(",
"'data'",
",",
"''",
")",
"query",
"=",
"'''INSERT INTO {keyspa... | Return event to one of potentially many clustered cassandra nodes
Requires that configuration be enabled via 'event_return'
option in master config.
Cassandra does not support an auto-increment feature due to the
highly inefficient nature of creating a monotonically increasing
number across all nodes in a distributed database. Each event
will be assigned a uuid by the connecting client. | [
"Return",
"event",
"to",
"one",
"of",
"potentially",
"many",
"clustered",
"cassandra",
"nodes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L246-L283 | train |
saltstack/salt | salt/returners/cassandra_cql_return.py | save_load | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
# Load is being stored as a text datatype. Single quotes are used in the
# VALUES list. Therefore, all single quotes contained in the results from
# salt.utils.json.dumps(load) must be escaped Cassandra style.
query = '''INSERT INTO {keyspace}.jids (
jid, load
) VALUES (?, ?)'''.format(keyspace=_get_keyspace())
statement_arguments = [
jid,
salt.utils.json.dumps(load).replace("'", "''")
]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load',
statement_arguments,
asynchronous=True)
except CommandExecutionError:
log.critical('Could not save load in jids table.')
raise
except Exception as e:
log.critical('Unexpected error while inserting into jids: %s', e)
raise | python | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
# Load is being stored as a text datatype. Single quotes are used in the
# VALUES list. Therefore, all single quotes contained in the results from
# salt.utils.json.dumps(load) must be escaped Cassandra style.
query = '''INSERT INTO {keyspace}.jids (
jid, load
) VALUES (?, ?)'''.format(keyspace=_get_keyspace())
statement_arguments = [
jid,
salt.utils.json.dumps(load).replace("'", "''")
]
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
__salt__['cassandra_cql.cql_query_with_prepare'](query, 'save_load',
statement_arguments,
asynchronous=True)
except CommandExecutionError:
log.critical('Could not save load in jids table.')
raise
except Exception as e:
log.critical('Unexpected error while inserting into jids: %s', e)
raise | [
"def",
"save_load",
"(",
"jid",
",",
"load",
",",
"minions",
"=",
"None",
")",
":",
"# Load is being stored as a text datatype. Single quotes are used in the",
"# VALUES list. Therefore, all single quotes contained in the results from",
"# salt.utils.json.dumps(load) must be escaped Cass... | Save the load to the specified jid id | [
"Save",
"the",
"load",
"to",
"the",
"specified",
"jid",
"id"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L286-L312 | train |
saltstack/salt | salt/returners/cassandra_cql_return.py | get_jid | def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns
WHERE jid = ?;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid])
if data:
for row in data:
minion = row.get('minion_id')
full_ret = row.get('full_ret')
if minion and full_ret:
ret[minion] = salt.utils.json.loads(full_ret)
except CommandExecutionError:
log.critical('Could not select job specific information.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting job specific information: %s', e)
raise
return ret | python | def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
query = '''SELECT minion_id, full_ret FROM {keyspace}.salt_returns
WHERE jid = ?;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query_with_prepare'](query, 'get_jid', [jid])
if data:
for row in data:
minion = row.get('minion_id')
full_ret = row.get('full_ret')
if minion and full_ret:
ret[minion] = salt.utils.json.loads(full_ret)
except CommandExecutionError:
log.critical('Could not select job specific information.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting job specific information: %s', e)
raise
return ret | [
"def",
"get_jid",
"(",
"jid",
")",
":",
"query",
"=",
"'''SELECT minion_id, full_ret FROM {keyspace}.salt_returns\n WHERE jid = ?;'''",
".",
"format",
"(",
"keyspace",
"=",
"_get_keyspace",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"# cassandra_cql.cql_query may ... | Return the information returned when the specified job id was executed | [
"Return",
"the",
"information",
"returned",
"when",
"the",
"specified",
"job",
"id",
"was",
"executed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L350-L376 | train |
saltstack/salt | salt/returners/cassandra_cql_return.py | get_fun | def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
query = '''SELECT minion_id, last_fun FROM {keyspace}.minions
WHERE last_fun = ?;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun])
if data:
for row in data:
minion = row.get('minion_id')
last_fun = row.get('last_fun')
if minion and last_fun:
ret[minion] = last_fun
except CommandExecutionError:
log.critical('Could not get the list of minions.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting list of minions: %s', e)
raise
return ret | python | def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
query = '''SELECT minion_id, last_fun FROM {keyspace}.minions
WHERE last_fun = ?;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](query, 'get_fun', [fun])
if data:
for row in data:
minion = row.get('minion_id')
last_fun = row.get('last_fun')
if minion and last_fun:
ret[minion] = last_fun
except CommandExecutionError:
log.critical('Could not get the list of minions.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting list of minions: %s', e)
raise
return ret | [
"def",
"get_fun",
"(",
"fun",
")",
":",
"query",
"=",
"'''SELECT minion_id, last_fun FROM {keyspace}.minions\n WHERE last_fun = ?;'''",
".",
"format",
"(",
"keyspace",
"=",
"_get_keyspace",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"# cassandra_cql.cql_query may ... | Return a dict of the last function called for all minions | [
"Return",
"a",
"dict",
"of",
"the",
"last",
"function",
"called",
"for",
"all",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L380-L406 | train |
saltstack/salt | salt/returners/cassandra_cql_return.py | get_jids | def get_jids():
'''
Return a list of all job ids
'''
query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](query)
if data:
for row in data:
jid = row.get('jid')
load = row.get('load')
if jid and load:
ret[jid] = salt.utils.jid.format_jid_instance(
jid,
salt.utils.json.loads(load))
except CommandExecutionError:
log.critical('Could not get a list of all job ids.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting list of all job ids: %s', e)
raise
return ret | python | def get_jids():
'''
Return a list of all job ids
'''
query = '''SELECT jid, load FROM {keyspace}.jids;'''.format(keyspace=_get_keyspace())
ret = {}
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](query)
if data:
for row in data:
jid = row.get('jid')
load = row.get('load')
if jid and load:
ret[jid] = salt.utils.jid.format_jid_instance(
jid,
salt.utils.json.loads(load))
except CommandExecutionError:
log.critical('Could not get a list of all job ids.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting list of all job ids: %s', e)
raise
return ret | [
"def",
"get_jids",
"(",
")",
":",
"query",
"=",
"'''SELECT jid, load FROM {keyspace}.jids;'''",
".",
"format",
"(",
"keyspace",
"=",
"_get_keyspace",
"(",
")",
")",
"ret",
"=",
"{",
"}",
"# cassandra_cql.cql_query may raise a CommandExecutionError",
"try",
":",
"data"... | Return a list of all job ids | [
"Return",
"a",
"list",
"of",
"all",
"job",
"ids"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L410-L437 | train |
saltstack/salt | salt/returners/cassandra_cql_return.py | get_minions | def get_minions():
'''
Return a list of minions
'''
query = '''SELECT DISTINCT minion_id
FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace())
ret = []
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](query)
if data:
for row in data:
minion = row.get('minion_id')
if minion:
ret.append(minion)
except CommandExecutionError:
log.critical('Could not get the list of minions.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting list of minions: %s', e)
raise
return ret | python | def get_minions():
'''
Return a list of minions
'''
query = '''SELECT DISTINCT minion_id
FROM {keyspace}.minions;'''.format(keyspace=_get_keyspace())
ret = []
# cassandra_cql.cql_query may raise a CommandExecutionError
try:
data = __salt__['cassandra_cql.cql_query'](query)
if data:
for row in data:
minion = row.get('minion_id')
if minion:
ret.append(minion)
except CommandExecutionError:
log.critical('Could not get the list of minions.')
raise
except Exception as e:
log.critical(
'Unexpected error while getting list of minions: %s', e)
raise
return ret | [
"def",
"get_minions",
"(",
")",
":",
"query",
"=",
"'''SELECT DISTINCT minion_id\n FROM {keyspace}.minions;'''",
".",
"format",
"(",
"keyspace",
"=",
"_get_keyspace",
"(",
")",
")",
"ret",
"=",
"[",
"]",
"# cassandra_cql.cql_query may raise a CommandExecutionE... | Return a list of minions | [
"Return",
"a",
"list",
"of",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/cassandra_cql_return.py#L441-L466 | train |
saltstack/salt | salt/output/json_out.py | output | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print the output data in JSON
'''
try:
if 'output_indent' not in __opts__:
return salt.utils.json.dumps(data, default=repr, indent=4)
indent = __opts__.get('output_indent')
sort_keys = False
if indent is None:
indent = None
elif indent == 'pretty':
indent = 4
sort_keys = True
elif isinstance(indent, int):
if indent >= 0:
indent = indent
else:
indent = None
return salt.utils.json.dumps(data, default=repr, indent=indent, sort_keys=sort_keys)
except UnicodeDecodeError as exc:
log.error('Unable to serialize output to json')
return salt.utils.json.dumps(
{'error': 'Unable to serialize output to json',
'message': six.text_type(exc)}
)
except TypeError:
log.debug('An error occurred while outputting JSON', exc_info=True)
# Return valid JSON for unserializable objects
return salt.utils.json.dumps({}) | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print the output data in JSON
'''
try:
if 'output_indent' not in __opts__:
return salt.utils.json.dumps(data, default=repr, indent=4)
indent = __opts__.get('output_indent')
sort_keys = False
if indent is None:
indent = None
elif indent == 'pretty':
indent = 4
sort_keys = True
elif isinstance(indent, int):
if indent >= 0:
indent = indent
else:
indent = None
return salt.utils.json.dumps(data, default=repr, indent=indent, sort_keys=sort_keys)
except UnicodeDecodeError as exc:
log.error('Unable to serialize output to json')
return salt.utils.json.dumps(
{'error': 'Unable to serialize output to json',
'message': six.text_type(exc)}
)
except TypeError:
log.debug('An error occurred while outputting JSON', exc_info=True)
# Return valid JSON for unserializable objects
return salt.utils.json.dumps({}) | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"try",
":",
"if",
"'output_indent'",
"not",
"in",
"__opts__",
":",
"return",
"salt",
".",
"utils",
".",
"json",
".",
"dumps",
"(",
"data",
",",
"default",... | Print the output data in JSON | [
"Print",
"the",
"output",
"data",
"in",
"JSON"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/json_out.py#L56-L92 | train |
saltstack/salt | salt/states/mssql_role.py | present | def present(name, owner=None, grants=None, **kwargs):
'''
Ensure that the named database is present with the specified options
name
The name of the database to manage
owner
Adds owner using AUTHORIZATION option
Grants
Can only be a list of strings
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if __salt__['mssql.role_exists'](name, **kwargs):
ret['comment'] = 'Role {0} is already present (Not going to try to set its grants)'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Role {0} is set to be added'.format(name)
return ret
role_created = __salt__['mssql.role_create'](name, owner=owner, grants=grants, **kwargs)
if role_created is not True: # Non-empty strings are also evaluated to True, so we cannot use if not role_created:
ret['result'] = False
ret['comment'] += 'Role {0} failed to be created: {1}'.format(name, role_created)
return ret
ret['comment'] += 'Role {0} has been added'.format(name)
ret['changes'][name] = 'Present'
return ret | python | def present(name, owner=None, grants=None, **kwargs):
'''
Ensure that the named database is present with the specified options
name
The name of the database to manage
owner
Adds owner using AUTHORIZATION option
Grants
Can only be a list of strings
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if __salt__['mssql.role_exists'](name, **kwargs):
ret['comment'] = 'Role {0} is already present (Not going to try to set its grants)'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Role {0} is set to be added'.format(name)
return ret
role_created = __salt__['mssql.role_create'](name, owner=owner, grants=grants, **kwargs)
if role_created is not True: # Non-empty strings are also evaluated to True, so we cannot use if not role_created:
ret['result'] = False
ret['comment'] += 'Role {0} failed to be created: {1}'.format(name, role_created)
return ret
ret['comment'] += 'Role {0} has been added'.format(name)
ret['changes'][name] = 'Present'
return ret | [
"def",
"present",
"(",
"name",
",",
"owner",
"=",
"None",
",",
"grants",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",... | Ensure that the named database is present with the specified options
name
The name of the database to manage
owner
Adds owner using AUTHORIZATION option
Grants
Can only be a list of strings | [
"Ensure",
"that",
"the",
"named",
"database",
"is",
"present",
"with",
"the",
"specified",
"options"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/mssql_role.py#L24-L55 | train |
saltstack/salt | salt/modules/servicenow.py | set_change_request_state | def set_change_request_state(change_id, state='approved'):
'''
Set the approval state of a change request/record
:param change_id: The ID of the change request, e.g. CHG123545
:type change_id: ``str``
:param state: The target state, e.g. approved
:type state: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.set_change_request_state CHG000123 declined
salt myminion servicenow.set_change_request_state CHG000123 approved
'''
client = _get_client()
client.table = 'change_request'
# Get the change record first
record = client.get({'number': change_id})
if not record:
log.error('Failed to fetch change record, maybe it does not exist?')
return False
# Use the sys_id as the unique system record
sys_id = record[0]['sys_id']
response = client.update({'approval': state}, sys_id)
return response | python | def set_change_request_state(change_id, state='approved'):
'''
Set the approval state of a change request/record
:param change_id: The ID of the change request, e.g. CHG123545
:type change_id: ``str``
:param state: The target state, e.g. approved
:type state: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.set_change_request_state CHG000123 declined
salt myminion servicenow.set_change_request_state CHG000123 approved
'''
client = _get_client()
client.table = 'change_request'
# Get the change record first
record = client.get({'number': change_id})
if not record:
log.error('Failed to fetch change record, maybe it does not exist?')
return False
# Use the sys_id as the unique system record
sys_id = record[0]['sys_id']
response = client.update({'approval': state}, sys_id)
return response | [
"def",
"set_change_request_state",
"(",
"change_id",
",",
"state",
"=",
"'approved'",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"client",
".",
"table",
"=",
"'change_request'",
"# Get the change record first",
"record",
"=",
"client",
".",
"get",
"(",
"{... | Set the approval state of a change request/record
:param change_id: The ID of the change request, e.g. CHG123545
:type change_id: ``str``
:param state: The target state, e.g. approved
:type state: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.set_change_request_state CHG000123 declined
salt myminion servicenow.set_change_request_state CHG000123 approved | [
"Set",
"the",
"approval",
"state",
"of",
"a",
"change",
"request",
"/",
"record"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L61-L88 | train |
saltstack/salt | salt/modules/servicenow.py | delete_record | def delete_record(table, sys_id):
'''
Delete an existing record
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.delete_record sys_computer 2134566
'''
client = _get_client()
client.table = table
response = client.delete(sys_id)
return response | python | def delete_record(table, sys_id):
'''
Delete an existing record
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.delete_record sys_computer 2134566
'''
client = _get_client()
client.table = table
response = client.delete(sys_id)
return response | [
"def",
"delete_record",
"(",
"table",
",",
"sys_id",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"client",
".",
"table",
"=",
"table",
"response",
"=",
"client",
".",
"delete",
"(",
"sys_id",
")",
"return",
"response"
] | Delete an existing record
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.delete_record sys_computer 2134566 | [
"Delete",
"an",
"existing",
"record"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L91-L110 | train |
saltstack/salt | salt/modules/servicenow.py | non_structured_query | def non_structured_query(table, query=None, **kwargs):
'''
Run a non-structed (not a dict) query on a servicenow table.
See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0
for help on constructing a non-structured query string.
:param table: The table name, e.g. sys_user
:type table: ``str``
:param query: The query to run (or use keyword arguments to filter data)
:type query: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.non_structured_query sys_computer 'role=web'
salt myminion servicenow.non_structured_query sys_computer role=web type=computer
'''
client = _get_client()
client.table = table
# underlying lib doesn't use six or past.basestring,
# does isinstance(x, str)
# http://bit.ly/1VkMmpE
if query is None:
# try and assemble a query by keyword
query_parts = []
for key, value in kwargs.items():
query_parts.append('{0}={1}'.format(key, value))
query = '^'.join(query_parts)
query = six.text_type(query)
response = client.get(query)
return response | python | def non_structured_query(table, query=None, **kwargs):
'''
Run a non-structed (not a dict) query on a servicenow table.
See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0
for help on constructing a non-structured query string.
:param table: The table name, e.g. sys_user
:type table: ``str``
:param query: The query to run (or use keyword arguments to filter data)
:type query: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.non_structured_query sys_computer 'role=web'
salt myminion servicenow.non_structured_query sys_computer role=web type=computer
'''
client = _get_client()
client.table = table
# underlying lib doesn't use six or past.basestring,
# does isinstance(x, str)
# http://bit.ly/1VkMmpE
if query is None:
# try and assemble a query by keyword
query_parts = []
for key, value in kwargs.items():
query_parts.append('{0}={1}'.format(key, value))
query = '^'.join(query_parts)
query = six.text_type(query)
response = client.get(query)
return response | [
"def",
"non_structured_query",
"(",
"table",
",",
"query",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"client",
".",
"table",
"=",
"table",
"# underlying lib doesn't use six or past.basestring,",
"# does isinstance(x, str... | Run a non-structed (not a dict) query on a servicenow table.
See http://wiki.servicenow.com/index.php?title=Encoded_Query_Strings#gsc.tab=0
for help on constructing a non-structured query string.
:param table: The table name, e.g. sys_user
:type table: ``str``
:param query: The query to run (or use keyword arguments to filter data)
:type query: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.non_structured_query sys_computer 'role=web'
salt myminion servicenow.non_structured_query sys_computer role=web type=computer | [
"Run",
"a",
"non",
"-",
"structed",
"(",
"not",
"a",
"dict",
")",
"query",
"on",
"a",
"servicenow",
"table",
".",
"See",
"http",
":",
"//",
"wiki",
".",
"servicenow",
".",
"com",
"/",
"index",
".",
"php?title",
"=",
"Encoded_Query_Strings#gsc",
".",
"t... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L113-L145 | train |
saltstack/salt | salt/modules/servicenow.py | update_record_field | def update_record_field(table, sys_id, field, value):
'''
Update the value of a record's field in a servicenow table
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
:param field: The new value
:type field: ``str``
:param value: The new value
:type value: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy
'''
client = _get_client()
client.table = table
response = client.update({field: value}, sys_id)
return response | python | def update_record_field(table, sys_id, field, value):
'''
Update the value of a record's field in a servicenow table
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
:param field: The new value
:type field: ``str``
:param value: The new value
:type value: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy
'''
client = _get_client()
client.table = table
response = client.update({field: value}, sys_id)
return response | [
"def",
"update_record_field",
"(",
"table",
",",
"sys_id",
",",
"field",
",",
"value",
")",
":",
"client",
"=",
"_get_client",
"(",
")",
"client",
".",
"table",
"=",
"table",
"response",
"=",
"client",
".",
"update",
"(",
"{",
"field",
":",
"value",
"}... | Update the value of a record's field in a servicenow table
:param table: The table name, e.g. sys_user
:type table: ``str``
:param sys_id: The unique ID of the record
:type sys_id: ``str``
:param field: The new value
:type field: ``str``
:param value: The new value
:type value: ``str``
CLI Example:
.. code-block:: bash
salt myminion servicenow.update_record_field sys_user 2348234 first_name jimmy | [
"Update",
"the",
"value",
"of",
"a",
"record",
"s",
"field",
"in",
"a",
"servicenow",
"table"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/servicenow.py#L148-L173 | train |
saltstack/salt | salt/states/cabal.py | _parse_pkg_string | def _parse_pkg_string(pkg):
'''
Parse pkg string and return a tuple of package name, separator, and
package version.
Cabal support install package with following format:
* foo-1.0
* foo < 1.2
* foo > 1.3
For the sake of simplicity only the first form is supported,
support for other forms can be added later.
'''
pkg_name, separator, pkg_ver = pkg.partition('-')
return (pkg_name.strip(), separator, pkg_ver.strip()) | python | def _parse_pkg_string(pkg):
'''
Parse pkg string and return a tuple of package name, separator, and
package version.
Cabal support install package with following format:
* foo-1.0
* foo < 1.2
* foo > 1.3
For the sake of simplicity only the first form is supported,
support for other forms can be added later.
'''
pkg_name, separator, pkg_ver = pkg.partition('-')
return (pkg_name.strip(), separator, pkg_ver.strip()) | [
"def",
"_parse_pkg_string",
"(",
"pkg",
")",
":",
"pkg_name",
",",
"separator",
",",
"pkg_ver",
"=",
"pkg",
".",
"partition",
"(",
"'-'",
")",
"return",
"(",
"pkg_name",
".",
"strip",
"(",
")",
",",
"separator",
",",
"pkg_ver",
".",
"strip",
"(",
")",
... | Parse pkg string and return a tuple of package name, separator, and
package version.
Cabal support install package with following format:
* foo-1.0
* foo < 1.2
* foo > 1.3
For the sake of simplicity only the first form is supported,
support for other forms can be added later. | [
"Parse",
"pkg",
"string",
"and",
"return",
"a",
"tuple",
"of",
"package",
"name",
"separator",
"and",
"package",
"version",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cabal.py#L40-L55 | train |
saltstack/salt | salt/states/cabal.py | installed | def installed(name,
pkgs=None,
user=None,
install_global=False,
env=None):
'''
Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
ShellCheck-0.3.5:
cabal:
- installed:
name
The package to install
user
The user to run cabal install with
install_global
Install package globally instead of locally
env
A list of environment variables to be set prior to execution. The
format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`.
state function.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
try:
call = __salt__['cabal.update'](user=user, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Could not run cabal update {0}'.format(err)
return ret
if pkgs is not None:
pkg_list = pkgs
else:
pkg_list = [name]
try:
installed_pkgs = __salt__['cabal.list'](
user=user, installed=True, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err)
return ret
pkgs_satisfied = []
pkgs_to_install = []
for pkg in pkg_list:
pkg_name, _, pkg_ver = _parse_pkg_string(pkg)
if pkg_name not in installed_pkgs:
pkgs_to_install.append(pkg)
else:
if pkg_ver: # version is specified
if installed_pkgs[pkg_name] != pkg_ver:
pkgs_to_install.append(pkg)
else:
pkgs_satisfied.append(pkg)
else:
pkgs_satisfied.append(pkg)
if __opts__['test']:
ret['result'] = None
comment_msg = []
if pkgs_to_install:
comment_msg.append(
'Packages(s) \'{0}\' are set to be installed'.format(
', '.join(pkgs_to_install)))
if pkgs_satisfied:
comment_msg.append(
'Packages(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
ret['comment'] = '. '.join(comment_msg)
return ret
if not pkgs_to_install:
ret['result'] = True
ret['comment'] = ('Packages(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
return ret
try:
call = __salt__['cabal.install'](pkgs=pkg_list,
user=user,
install_global=install_global,
env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error installing \'{0}\': {1}'.format(
', '.join(pkg_list), err)
return ret
if call and isinstance(call, dict):
ret['result'] = True
ret['changes'] = {'old': [], 'new': pkgs_to_install}
ret['comment'] = 'Packages(s) \'{0}\' successfully installed'.format(
', '.join(pkgs_to_install))
else:
ret['result'] = False
ret['comment'] = 'Could not install packages(s) \'{0}\''.format(
', '.join(pkg_list))
return ret | python | def installed(name,
pkgs=None,
user=None,
install_global=False,
env=None):
'''
Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
ShellCheck-0.3.5:
cabal:
- installed:
name
The package to install
user
The user to run cabal install with
install_global
Install package globally instead of locally
env
A list of environment variables to be set prior to execution. The
format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`.
state function.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
try:
call = __salt__['cabal.update'](user=user, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Could not run cabal update {0}'.format(err)
return ret
if pkgs is not None:
pkg_list = pkgs
else:
pkg_list = [name]
try:
installed_pkgs = __salt__['cabal.list'](
user=user, installed=True, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err)
return ret
pkgs_satisfied = []
pkgs_to_install = []
for pkg in pkg_list:
pkg_name, _, pkg_ver = _parse_pkg_string(pkg)
if pkg_name not in installed_pkgs:
pkgs_to_install.append(pkg)
else:
if pkg_ver: # version is specified
if installed_pkgs[pkg_name] != pkg_ver:
pkgs_to_install.append(pkg)
else:
pkgs_satisfied.append(pkg)
else:
pkgs_satisfied.append(pkg)
if __opts__['test']:
ret['result'] = None
comment_msg = []
if pkgs_to_install:
comment_msg.append(
'Packages(s) \'{0}\' are set to be installed'.format(
', '.join(pkgs_to_install)))
if pkgs_satisfied:
comment_msg.append(
'Packages(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
ret['comment'] = '. '.join(comment_msg)
return ret
if not pkgs_to_install:
ret['result'] = True
ret['comment'] = ('Packages(s) \'{0}\' satisfied by {1}'.format(
', '.join(pkg_list), ', '.join(pkgs_satisfied)))
return ret
try:
call = __salt__['cabal.install'](pkgs=pkg_list,
user=user,
install_global=install_global,
env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error installing \'{0}\': {1}'.format(
', '.join(pkg_list), err)
return ret
if call and isinstance(call, dict):
ret['result'] = True
ret['changes'] = {'old': [], 'new': pkgs_to_install}
ret['comment'] = 'Packages(s) \'{0}\' successfully installed'.format(
', '.join(pkgs_to_install))
else:
ret['result'] = False
ret['comment'] = 'Could not install packages(s) \'{0}\''.format(
', '.join(pkg_list))
return ret | [
"def",
"installed",
"(",
"name",
",",
"pkgs",
"=",
"None",
",",
"user",
"=",
"None",
",",
"install_global",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":"... | Verify that the given package is installed and is at the correct version
(if specified).
.. code-block:: yaml
ShellCheck-0.3.5:
cabal:
- installed:
name
The package to install
user
The user to run cabal install with
install_global
Install package globally instead of locally
env
A list of environment variables to be set prior to execution. The
format is the same as the :py:func:`cmd.run <salt.states.cmd.run>`.
state function. | [
"Verify",
"that",
"the",
"given",
"package",
"is",
"installed",
"and",
"is",
"at",
"the",
"correct",
"version",
"(",
"if",
"specified",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cabal.py#L58-L169 | train |
saltstack/salt | salt/states/cabal.py | removed | def removed(name,
user=None,
env=None):
'''
Verify that given package is not installed.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
try:
installed_pkgs = __salt__['cabal.list'](
user=user, installed=True, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err)
if name not in installed_pkgs:
ret['result'] = True
ret['comment'] = 'Package \'{0}\' is not installed'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Package \'{0}\' is set to be removed'.format(name)
return ret
if __salt__['cabal.uninstall'](pkg=name, user=user, env=env):
ret['result'] = True
ret['changes'][name] = 'Removed'
ret['comment'] = 'Package \'{0}\' was successfully removed'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Error removing package \'{0}\''.format(name)
return ret | python | def removed(name,
user=None,
env=None):
'''
Verify that given package is not installed.
'''
ret = {'name': name, 'result': None, 'comment': '', 'changes': {}}
try:
installed_pkgs = __salt__['cabal.list'](
user=user, installed=True, env=env)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error looking up \'{0}\': {1}'.format(name, err)
if name not in installed_pkgs:
ret['result'] = True
ret['comment'] = 'Package \'{0}\' is not installed'.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Package \'{0}\' is set to be removed'.format(name)
return ret
if __salt__['cabal.uninstall'](pkg=name, user=user, env=env):
ret['result'] = True
ret['changes'][name] = 'Removed'
ret['comment'] = 'Package \'{0}\' was successfully removed'.format(name)
else:
ret['result'] = False
ret['comment'] = 'Error removing package \'{0}\''.format(name)
return ret | [
"def",
"removed",
"(",
"name",
",",
"user",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"try",
":",
"in... | Verify that given package is not installed. | [
"Verify",
"that",
"given",
"package",
"is",
"not",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cabal.py#L172-L206 | train |
saltstack/salt | salt/beacons/service.py | beacon | def beacon(config):
'''
Scan for the configured services and fire events
Example Config
.. code-block:: yaml
beacons:
service:
- services:
salt-master: {}
mysql: {}
The config above sets up beacons to check for
the salt-master and mysql services.
The config also supports two other parameters for each service:
`onchangeonly`: when `onchangeonly` is True the beacon will fire
events only when the service status changes. Otherwise, it will fire an
event at each beacon interval. The default is False.
`delay`: when `delay` is greater than 0 the beacon will fire events only
after the service status changes, and the delay (in seconds) has passed.
Applicable only when `onchangeonly` is True. The default is 0.
`emitatstartup`: when `emitatstartup` is False the beacon will not fire
event when the minion is reload. Applicable only when `onchangeonly` is True.
The default is True.
`uncleanshutdown`: If `uncleanshutdown` is present it should point to the
location of a pid file for the service. Most services will not clean up
this pid file if they are shutdown uncleanly (e.g. via `kill -9`) or if they
are terminated through a crash such as a segmentation fault. If the file is
present, then the beacon will add `uncleanshutdown: True` to the event. If
not present, the field will be False. The field is only added when the
service is NOT running. Omitting the configuration variable altogether will
turn this feature off.
Please note that some init systems can remove the pid file if the service
registers as crashed. One such example is nginx on CentOS 7, where the
service unit removes the pid file when the service shuts down (IE: the pid
file is observed as removed when kill -9 is sent to the nginx master
process). The 'uncleanshutdown' option might not be of much use there,
unless the unit file is modified.
Here is an example that will fire an event 30 seconds after the state of nginx
changes and report an uncleanshutdown. This example is for Arch, which
places nginx's pid file in `/run`.
.. code-block:: yaml
beacons:
service:
- services:
nginx:
onchangeonly: True
delay: 30
uncleanshutdown: /run/nginx.pid
'''
ret = []
_config = {}
list(map(_config.update, config))
for service in _config.get('services', {}):
ret_dict = {}
service_config = _config['services'][service]
ret_dict[service] = {'running': __salt__['service.status'](service)}
ret_dict['service_name'] = service
ret_dict['tag'] = service
currtime = time.time()
# If no options is given to the service, we fall back to the defaults
# assign a False value to oncleanshutdown and onchangeonly. Those
# key:values are then added to the service dictionary.
if not service_config:
service_config = {}
if 'oncleanshutdown' not in service_config:
service_config['oncleanshutdown'] = False
if 'emitatstartup' not in service_config:
service_config['emitatstartup'] = True
if 'onchangeonly' not in service_config:
service_config['onchangeonly'] = False
if 'delay' not in service_config:
service_config['delay'] = 0
# We only want to report the nature of the shutdown
# if the current running status is False
# as well as if the config for the beacon asks for it
if 'uncleanshutdown' in service_config and not ret_dict[service]['running']:
filename = service_config['uncleanshutdown']
ret_dict[service]['uncleanshutdown'] = True if os.path.exists(filename) else False
if 'onchangeonly' in service_config and service_config['onchangeonly'] is True:
if service not in LAST_STATUS:
LAST_STATUS[service] = ret_dict[service]
if service_config['delay'] > 0:
LAST_STATUS[service]['time'] = currtime
elif not service_config['emitatstartup']:
continue
else:
ret.append(ret_dict)
if LAST_STATUS[service]['running'] != ret_dict[service]['running']:
LAST_STATUS[service] = ret_dict[service]
if service_config['delay'] > 0:
LAST_STATUS[service]['time'] = currtime
else:
ret.append(ret_dict)
if 'time' in LAST_STATUS[service]:
elapsedtime = int(round(currtime - LAST_STATUS[service]['time']))
if elapsedtime > service_config['delay']:
del LAST_STATUS[service]['time']
ret.append(ret_dict)
else:
ret.append(ret_dict)
return ret | python | def beacon(config):
'''
Scan for the configured services and fire events
Example Config
.. code-block:: yaml
beacons:
service:
- services:
salt-master: {}
mysql: {}
The config above sets up beacons to check for
the salt-master and mysql services.
The config also supports two other parameters for each service:
`onchangeonly`: when `onchangeonly` is True the beacon will fire
events only when the service status changes. Otherwise, it will fire an
event at each beacon interval. The default is False.
`delay`: when `delay` is greater than 0 the beacon will fire events only
after the service status changes, and the delay (in seconds) has passed.
Applicable only when `onchangeonly` is True. The default is 0.
`emitatstartup`: when `emitatstartup` is False the beacon will not fire
event when the minion is reload. Applicable only when `onchangeonly` is True.
The default is True.
`uncleanshutdown`: If `uncleanshutdown` is present it should point to the
location of a pid file for the service. Most services will not clean up
this pid file if they are shutdown uncleanly (e.g. via `kill -9`) or if they
are terminated through a crash such as a segmentation fault. If the file is
present, then the beacon will add `uncleanshutdown: True` to the event. If
not present, the field will be False. The field is only added when the
service is NOT running. Omitting the configuration variable altogether will
turn this feature off.
Please note that some init systems can remove the pid file if the service
registers as crashed. One such example is nginx on CentOS 7, where the
service unit removes the pid file when the service shuts down (IE: the pid
file is observed as removed when kill -9 is sent to the nginx master
process). The 'uncleanshutdown' option might not be of much use there,
unless the unit file is modified.
Here is an example that will fire an event 30 seconds after the state of nginx
changes and report an uncleanshutdown. This example is for Arch, which
places nginx's pid file in `/run`.
.. code-block:: yaml
beacons:
service:
- services:
nginx:
onchangeonly: True
delay: 30
uncleanshutdown: /run/nginx.pid
'''
ret = []
_config = {}
list(map(_config.update, config))
for service in _config.get('services', {}):
ret_dict = {}
service_config = _config['services'][service]
ret_dict[service] = {'running': __salt__['service.status'](service)}
ret_dict['service_name'] = service
ret_dict['tag'] = service
currtime = time.time()
# If no options is given to the service, we fall back to the defaults
# assign a False value to oncleanshutdown and onchangeonly. Those
# key:values are then added to the service dictionary.
if not service_config:
service_config = {}
if 'oncleanshutdown' not in service_config:
service_config['oncleanshutdown'] = False
if 'emitatstartup' not in service_config:
service_config['emitatstartup'] = True
if 'onchangeonly' not in service_config:
service_config['onchangeonly'] = False
if 'delay' not in service_config:
service_config['delay'] = 0
# We only want to report the nature of the shutdown
# if the current running status is False
# as well as if the config for the beacon asks for it
if 'uncleanshutdown' in service_config and not ret_dict[service]['running']:
filename = service_config['uncleanshutdown']
ret_dict[service]['uncleanshutdown'] = True if os.path.exists(filename) else False
if 'onchangeonly' in service_config and service_config['onchangeonly'] is True:
if service not in LAST_STATUS:
LAST_STATUS[service] = ret_dict[service]
if service_config['delay'] > 0:
LAST_STATUS[service]['time'] = currtime
elif not service_config['emitatstartup']:
continue
else:
ret.append(ret_dict)
if LAST_STATUS[service]['running'] != ret_dict[service]['running']:
LAST_STATUS[service] = ret_dict[service]
if service_config['delay'] > 0:
LAST_STATUS[service]['time'] = currtime
else:
ret.append(ret_dict)
if 'time' in LAST_STATUS[service]:
elapsedtime = int(round(currtime - LAST_STATUS[service]['time']))
if elapsedtime > service_config['delay']:
del LAST_STATUS[service]['time']
ret.append(ret_dict)
else:
ret.append(ret_dict)
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"for",
"service",
"in",
"_config",
".",
"get",
"(",
"'services'",
",",
"{",
"}",... | Scan for the configured services and fire events
Example Config
.. code-block:: yaml
beacons:
service:
- services:
salt-master: {}
mysql: {}
The config above sets up beacons to check for
the salt-master and mysql services.
The config also supports two other parameters for each service:
`onchangeonly`: when `onchangeonly` is True the beacon will fire
events only when the service status changes. Otherwise, it will fire an
event at each beacon interval. The default is False.
`delay`: when `delay` is greater than 0 the beacon will fire events only
after the service status changes, and the delay (in seconds) has passed.
Applicable only when `onchangeonly` is True. The default is 0.
`emitatstartup`: when `emitatstartup` is False the beacon will not fire
event when the minion is reload. Applicable only when `onchangeonly` is True.
The default is True.
`uncleanshutdown`: If `uncleanshutdown` is present it should point to the
location of a pid file for the service. Most services will not clean up
this pid file if they are shutdown uncleanly (e.g. via `kill -9`) or if they
are terminated through a crash such as a segmentation fault. If the file is
present, then the beacon will add `uncleanshutdown: True` to the event. If
not present, the field will be False. The field is only added when the
service is NOT running. Omitting the configuration variable altogether will
turn this feature off.
Please note that some init systems can remove the pid file if the service
registers as crashed. One such example is nginx on CentOS 7, where the
service unit removes the pid file when the service shuts down (IE: the pid
file is observed as removed when kill -9 is sent to the nginx master
process). The 'uncleanshutdown' option might not be of much use there,
unless the unit file is modified.
Here is an example that will fire an event 30 seconds after the state of nginx
changes and report an uncleanshutdown. This example is for Arch, which
places nginx's pid file in `/run`.
.. code-block:: yaml
beacons:
service:
- services:
nginx:
onchangeonly: True
delay: 30
uncleanshutdown: /run/nginx.pid | [
"Scan",
"for",
"the",
"configured",
"services",
"and",
"fire",
"events"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/service.py#L44-L164 | train |
saltstack/salt | salt/modules/jira_mod.py | _get_credentials | def _get_credentials(server=None,
username=None,
password=None):
'''
Returns the credentials merged with the config data (opts + pillar).
'''
jira_cfg = __salt__['config.merge']('jira', default={})
if not server:
server = jira_cfg.get('server')
if not username:
username = jira_cfg.get('username')
if not password:
password = jira_cfg.get('password')
return server, username, password | python | def _get_credentials(server=None,
username=None,
password=None):
'''
Returns the credentials merged with the config data (opts + pillar).
'''
jira_cfg = __salt__['config.merge']('jira', default={})
if not server:
server = jira_cfg.get('server')
if not username:
username = jira_cfg.get('username')
if not password:
password = jira_cfg.get('password')
return server, username, password | [
"def",
"_get_credentials",
"(",
"server",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"jira_cfg",
"=",
"__salt__",
"[",
"'config.merge'",
"]",
"(",
"'jira'",
",",
"default",
"=",
"{",
"}",
")",
"if",
"not",
"serve... | Returns the credentials merged with the config data (opts + pillar). | [
"Returns",
"the",
"credentials",
"merged",
"with",
"the",
"config",
"data",
"(",
"opts",
"+",
"pillar",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L50-L63 | train |
saltstack/salt | salt/modules/jira_mod.py | create_issue | def create_issue(project,
summary,
description,
template_engine='jinja',
context=None,
defaults=None,
saltenv='base',
issuetype='Bug',
priority='Normal',
labels=None,
assignee=None,
server=None,
username=None,
password=None,
**kwargs):
'''
Create a JIRA issue using the named settings. Return the JIRA ticket ID.
project
The name of the project to attach the JIRA ticket to.
summary
The summary (title) of the JIRA ticket. When the ``template_engine``
argument is set to a proper value of an existing Salt template engine
(e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before
creating the ticket.
description
The full body description of the JIRA ticket. When the ``template_engine``
argument is set to a proper value of an existing Salt template engine
(e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before
creating the ticket.
template_engine: ``jinja``
The name of the template engine to be used to render the values of the
``summary`` and ``description`` arguments. Default: ``jinja``.
context: ``None``
The context to pass when rendering the ``summary`` and ``description``.
This argument is ignored when ``template_engine`` is set as ``None``
defaults: ``None``
Default values to pass to the Salt rendering pipeline for the
``summary`` and ``description`` arguments.
This argument is ignored when ``template_engine`` is set as ``None``.
saltenv: ``base``
The Salt environment name (for the rendering system).
issuetype: ``Bug``
The type of the JIRA ticket. Default: ``Bug``.
priority: ``Normal``
The priority of the JIRA ticket. Default: ``Normal``.
labels: ``None``
A list of labels to add to the ticket.
assignee: ``None``
The name of the person to assign the ticket to.
CLI Examples:
.. code-block:: bash
salt '*' jira.create_issue NET 'Ticket title' 'Ticket description'
salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja
'''
if template_engine:
summary = __salt__['file.apply_template_on_contents'](summary,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv)
description = __salt__['file.apply_template_on_contents'](description,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv)
jira_ = _get_jira(server=server,
username=username,
password=password)
if not labels:
labels = []
data = {
'project': {
'key': project
},
'summary': summary,
'description': description,
'issuetype': {
'name': issuetype
},
'priority': {
'name': priority
},
'labels': labels
}
data.update(clean_kwargs(**kwargs))
issue = jira_.create_issue(data)
issue_key = str(issue)
if assignee:
assign_issue(issue_key, assignee)
return issue_key | python | def create_issue(project,
summary,
description,
template_engine='jinja',
context=None,
defaults=None,
saltenv='base',
issuetype='Bug',
priority='Normal',
labels=None,
assignee=None,
server=None,
username=None,
password=None,
**kwargs):
'''
Create a JIRA issue using the named settings. Return the JIRA ticket ID.
project
The name of the project to attach the JIRA ticket to.
summary
The summary (title) of the JIRA ticket. When the ``template_engine``
argument is set to a proper value of an existing Salt template engine
(e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before
creating the ticket.
description
The full body description of the JIRA ticket. When the ``template_engine``
argument is set to a proper value of an existing Salt template engine
(e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before
creating the ticket.
template_engine: ``jinja``
The name of the template engine to be used to render the values of the
``summary`` and ``description`` arguments. Default: ``jinja``.
context: ``None``
The context to pass when rendering the ``summary`` and ``description``.
This argument is ignored when ``template_engine`` is set as ``None``
defaults: ``None``
Default values to pass to the Salt rendering pipeline for the
``summary`` and ``description`` arguments.
This argument is ignored when ``template_engine`` is set as ``None``.
saltenv: ``base``
The Salt environment name (for the rendering system).
issuetype: ``Bug``
The type of the JIRA ticket. Default: ``Bug``.
priority: ``Normal``
The priority of the JIRA ticket. Default: ``Normal``.
labels: ``None``
A list of labels to add to the ticket.
assignee: ``None``
The name of the person to assign the ticket to.
CLI Examples:
.. code-block:: bash
salt '*' jira.create_issue NET 'Ticket title' 'Ticket description'
salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja
'''
if template_engine:
summary = __salt__['file.apply_template_on_contents'](summary,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv)
description = __salt__['file.apply_template_on_contents'](description,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv)
jira_ = _get_jira(server=server,
username=username,
password=password)
if not labels:
labels = []
data = {
'project': {
'key': project
},
'summary': summary,
'description': description,
'issuetype': {
'name': issuetype
},
'priority': {
'name': priority
},
'labels': labels
}
data.update(clean_kwargs(**kwargs))
issue = jira_.create_issue(data)
issue_key = str(issue)
if assignee:
assign_issue(issue_key, assignee)
return issue_key | [
"def",
"create_issue",
"(",
"project",
",",
"summary",
",",
"description",
",",
"template_engine",
"=",
"'jinja'",
",",
"context",
"=",
"None",
",",
"defaults",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
",",
"issuetype",
"=",
"'Bug'",
",",
"priority",
"=... | Create a JIRA issue using the named settings. Return the JIRA ticket ID.
project
The name of the project to attach the JIRA ticket to.
summary
The summary (title) of the JIRA ticket. When the ``template_engine``
argument is set to a proper value of an existing Salt template engine
(e.g., ``jinja``, ``mako``, etc.) it will render the ``summary`` before
creating the ticket.
description
The full body description of the JIRA ticket. When the ``template_engine``
argument is set to a proper value of an existing Salt template engine
(e.g., ``jinja``, ``mako``, etc.) it will render the ``description`` before
creating the ticket.
template_engine: ``jinja``
The name of the template engine to be used to render the values of the
``summary`` and ``description`` arguments. Default: ``jinja``.
context: ``None``
The context to pass when rendering the ``summary`` and ``description``.
This argument is ignored when ``template_engine`` is set as ``None``
defaults: ``None``
Default values to pass to the Salt rendering pipeline for the
``summary`` and ``description`` arguments.
This argument is ignored when ``template_engine`` is set as ``None``.
saltenv: ``base``
The Salt environment name (for the rendering system).
issuetype: ``Bug``
The type of the JIRA ticket. Default: ``Bug``.
priority: ``Normal``
The priority of the JIRA ticket. Default: ``Normal``.
labels: ``None``
A list of labels to add to the ticket.
assignee: ``None``
The name of the person to assign the ticket to.
CLI Examples:
.. code-block:: bash
salt '*' jira.create_issue NET 'Ticket title' 'Ticket description'
salt '*' jira.create_issue NET 'Issue on {{ opts.id }}' 'Error detected on {{ opts.id }}' template_engine=jinja | [
"Create",
"a",
"JIRA",
"issue",
"using",
"the",
"named",
"settings",
".",
"Return",
"the",
"JIRA",
"ticket",
"ID",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L80-L183 | train |
saltstack/salt | salt/modules/jira_mod.py | assign_issue | def assign_issue(issue_key,
assignee,
server=None,
username=None,
password=None):
'''
Assign the issue to an existing user. Return ``True`` when the issue has
been properly assigned.
issue_key
The JIRA ID of the ticket to manipulate.
assignee
The name of the user to assign the ticket to.
CLI Example:
salt '*' jira.assign_issue NET-123 example_user
'''
jira_ = _get_jira(server=server,
username=username,
password=password)
assigned = jira_.assign_issue(issue_key, assignee)
return assigned | python | def assign_issue(issue_key,
assignee,
server=None,
username=None,
password=None):
'''
Assign the issue to an existing user. Return ``True`` when the issue has
been properly assigned.
issue_key
The JIRA ID of the ticket to manipulate.
assignee
The name of the user to assign the ticket to.
CLI Example:
salt '*' jira.assign_issue NET-123 example_user
'''
jira_ = _get_jira(server=server,
username=username,
password=password)
assigned = jira_.assign_issue(issue_key, assignee)
return assigned | [
"def",
"assign_issue",
"(",
"issue_key",
",",
"assignee",
",",
"server",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"jira_",
"=",
"_get_jira",
"(",
"server",
"=",
"server",
",",
"username",
"=",
"username",
",",
... | Assign the issue to an existing user. Return ``True`` when the issue has
been properly assigned.
issue_key
The JIRA ID of the ticket to manipulate.
assignee
The name of the user to assign the ticket to.
CLI Example:
salt '*' jira.assign_issue NET-123 example_user | [
"Assign",
"the",
"issue",
"to",
"an",
"existing",
"user",
".",
"Return",
"True",
"when",
"the",
"issue",
"has",
"been",
"properly",
"assigned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L186-L209 | train |
saltstack/salt | salt/modules/jira_mod.py | add_comment | def add_comment(issue_key,
comment,
visibility=None,
is_internal=False,
server=None,
username=None,
password=None):
'''
Add a comment to an existing ticket. Return ``True`` when it successfully
added the comment.
issue_key
The issue ID to add the comment to.
comment
The body of the comment to be added.
visibility: ``None``
A dictionary having two keys:
- ``type``: is ``role`` (or ``group`` if the JIRA server has configured
comment visibility for groups).
- ``value``: the name of the role (or group) to which viewing of this
comment will be restricted.
is_internal: ``False``
Whether a comment has to be marked as ``Internal`` in Jira Service Desk.
CLI Example:
.. code-block:: bash
salt '*' jira.add_comment NE-123 'This is a comment'
'''
jira_ = _get_jira(server=server,
username=username,
password=password)
comm = jira_.add_comment(issue_key,
comment,
visibility=visibility,
is_internal=is_internal)
return True | python | def add_comment(issue_key,
comment,
visibility=None,
is_internal=False,
server=None,
username=None,
password=None):
'''
Add a comment to an existing ticket. Return ``True`` when it successfully
added the comment.
issue_key
The issue ID to add the comment to.
comment
The body of the comment to be added.
visibility: ``None``
A dictionary having two keys:
- ``type``: is ``role`` (or ``group`` if the JIRA server has configured
comment visibility for groups).
- ``value``: the name of the role (or group) to which viewing of this
comment will be restricted.
is_internal: ``False``
Whether a comment has to be marked as ``Internal`` in Jira Service Desk.
CLI Example:
.. code-block:: bash
salt '*' jira.add_comment NE-123 'This is a comment'
'''
jira_ = _get_jira(server=server,
username=username,
password=password)
comm = jira_.add_comment(issue_key,
comment,
visibility=visibility,
is_internal=is_internal)
return True | [
"def",
"add_comment",
"(",
"issue_key",
",",
"comment",
",",
"visibility",
"=",
"None",
",",
"is_internal",
"=",
"False",
",",
"server",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"jira_",
"=",
"_get_jira",
"(",
... | Add a comment to an existing ticket. Return ``True`` when it successfully
added the comment.
issue_key
The issue ID to add the comment to.
comment
The body of the comment to be added.
visibility: ``None``
A dictionary having two keys:
- ``type``: is ``role`` (or ``group`` if the JIRA server has configured
comment visibility for groups).
- ``value``: the name of the role (or group) to which viewing of this
comment will be restricted.
is_internal: ``False``
Whether a comment has to be marked as ``Internal`` in Jira Service Desk.
CLI Example:
.. code-block:: bash
salt '*' jira.add_comment NE-123 'This is a comment' | [
"Add",
"a",
"comment",
"to",
"an",
"existing",
"ticket",
".",
"Return",
"True",
"when",
"it",
"successfully",
"added",
"the",
"comment",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L212-L253 | train |
saltstack/salt | salt/modules/jira_mod.py | issue_closed | def issue_closed(issue_key,
server=None,
username=None,
password=None):
'''
Check if the issue is closed.
issue_key
The JIRA iD of the ticket to close.
Returns:
- ``True``: the ticket exists and it is closed.
- ``False``: the ticket exists and it has not been closed.
- ``None``: the ticket does not exist.
CLI Example:
.. code-block:: bash
salt '*' jira.issue_closed NE-123
'''
if not issue_key:
return None
jira_ = _get_jira(server=server,
username=username,
password=password)
try:
ticket = jira_.issue(issue_key)
except jira.exceptions.JIRAError:
# Ticket not found
return None
return ticket.fields().status.name == 'Closed' | python | def issue_closed(issue_key,
server=None,
username=None,
password=None):
'''
Check if the issue is closed.
issue_key
The JIRA iD of the ticket to close.
Returns:
- ``True``: the ticket exists and it is closed.
- ``False``: the ticket exists and it has not been closed.
- ``None``: the ticket does not exist.
CLI Example:
.. code-block:: bash
salt '*' jira.issue_closed NE-123
'''
if not issue_key:
return None
jira_ = _get_jira(server=server,
username=username,
password=password)
try:
ticket = jira_.issue(issue_key)
except jira.exceptions.JIRAError:
# Ticket not found
return None
return ticket.fields().status.name == 'Closed' | [
"def",
"issue_closed",
"(",
"issue_key",
",",
"server",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"not",
"issue_key",
":",
"return",
"None",
"jira_",
"=",
"_get_jira",
"(",
"server",
"=",
"server",
",",
"u... | Check if the issue is closed.
issue_key
The JIRA iD of the ticket to close.
Returns:
- ``True``: the ticket exists and it is closed.
- ``False``: the ticket exists and it has not been closed.
- ``None``: the ticket does not exist.
CLI Example:
.. code-block:: bash
salt '*' jira.issue_closed NE-123 | [
"Check",
"if",
"the",
"issue",
"is",
"closed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jira_mod.py#L256-L288 | train |
saltstack/salt | salt/grains/junos.py | _remove_complex_types | def _remove_complex_types(dictionary):
'''
Linode-python is now returning some complex types that
are not serializable by msgpack. Kill those.
'''
for k, v in six.iteritems(dictionary):
if isinstance(v, dict):
dictionary[k] = _remove_complex_types(v)
elif hasattr(v, 'to_eng_string'):
dictionary[k] = v.to_eng_string()
return dictionary | python | def _remove_complex_types(dictionary):
'''
Linode-python is now returning some complex types that
are not serializable by msgpack. Kill those.
'''
for k, v in six.iteritems(dictionary):
if isinstance(v, dict):
dictionary[k] = _remove_complex_types(v)
elif hasattr(v, 'to_eng_string'):
dictionary[k] = v.to_eng_string()
return dictionary | [
"def",
"_remove_complex_types",
"(",
"dictionary",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"dictionary",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"dictionary",
"[",
"k",
"]",
"=",
"_remove_complex_types",... | Linode-python is now returning some complex types that
are not serializable by msgpack. Kill those. | [
"Linode",
"-",
"python",
"is",
"now",
"returning",
"some",
"complex",
"types",
"that",
"are",
"not",
"serializable",
"by",
"msgpack",
".",
"Kill",
"those",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/junos.py#L30-L41 | train |
saltstack/salt | salt/states/module.py | run | def run(**kwargs):
'''
Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the return data
:param kwargs:
Pass any arguments needed to execute the function(s)
.. code-block:: yaml
some_id_of_state:
module.run:
- network.ip_addrs:
- interface: eth0
- cloud.create:
- names:
- test-isbm-1
- test-isbm-2
- ssh_username: sles
- image: sles12sp2
- securitygroup: default
- size: 'c3.large'
- location: ap-northeast-1
- delvol_on_destroy: True
:return:
'''
if 'name' in kwargs:
kwargs.pop('name')
ret = {
'name': list(kwargs),
'changes': {},
'comment': '',
'result': None,
}
functions = [func for func in kwargs if '.' in func]
missing = []
tests = []
for func in functions:
func = func.split(':')[0]
if func not in __salt__:
missing.append(func)
elif __opts__['test']:
tests.append(func)
if tests or missing:
ret['comment'] = ' '.join([
missing and "Unavailable function{plr}: "
"{func}.".format(plr=(len(missing) > 1 or ''),
func=(', '.join(missing) or '')) or '',
tests and "Function{plr} {func} to be "
"executed.".format(plr=(len(tests) > 1 or ''),
func=(', '.join(tests)) or '') or '',
]).strip()
ret['result'] = not (missing or not tests)
if ret['result'] is None:
ret['result'] = True
failures = []
success = []
for func in functions:
_func = func.split(':')[0]
try:
func_ret = _call_function(_func, returner=kwargs.get('returner'),
func_args=kwargs.get(func))
if not _get_result(func_ret, ret['changes'].get('ret', {})):
if isinstance(func_ret, dict):
failures.append("'{0}' failed: {1}".format(
func, func_ret.get('comment', '(error message N/A)')))
else:
success.append('{0}: {1}'.format(
func, func_ret.get('comment', 'Success') if isinstance(func_ret, dict) else func_ret))
ret['changes'][func] = func_ret
except (SaltInvocationError, TypeError) as ex:
failures.append("'{0}' failed: {1}".format(func, ex))
ret['comment'] = ', '.join(failures + success)
ret['result'] = not bool(failures)
return ret | python | def run(**kwargs):
'''
Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the return data
:param kwargs:
Pass any arguments needed to execute the function(s)
.. code-block:: yaml
some_id_of_state:
module.run:
- network.ip_addrs:
- interface: eth0
- cloud.create:
- names:
- test-isbm-1
- test-isbm-2
- ssh_username: sles
- image: sles12sp2
- securitygroup: default
- size: 'c3.large'
- location: ap-northeast-1
- delvol_on_destroy: True
:return:
'''
if 'name' in kwargs:
kwargs.pop('name')
ret = {
'name': list(kwargs),
'changes': {},
'comment': '',
'result': None,
}
functions = [func for func in kwargs if '.' in func]
missing = []
tests = []
for func in functions:
func = func.split(':')[0]
if func not in __salt__:
missing.append(func)
elif __opts__['test']:
tests.append(func)
if tests or missing:
ret['comment'] = ' '.join([
missing and "Unavailable function{plr}: "
"{func}.".format(plr=(len(missing) > 1 or ''),
func=(', '.join(missing) or '')) or '',
tests and "Function{plr} {func} to be "
"executed.".format(plr=(len(tests) > 1 or ''),
func=(', '.join(tests)) or '') or '',
]).strip()
ret['result'] = not (missing or not tests)
if ret['result'] is None:
ret['result'] = True
failures = []
success = []
for func in functions:
_func = func.split(':')[0]
try:
func_ret = _call_function(_func, returner=kwargs.get('returner'),
func_args=kwargs.get(func))
if not _get_result(func_ret, ret['changes'].get('ret', {})):
if isinstance(func_ret, dict):
failures.append("'{0}' failed: {1}".format(
func, func_ret.get('comment', '(error message N/A)')))
else:
success.append('{0}: {1}'.format(
func, func_ret.get('comment', 'Success') if isinstance(func_ret, dict) else func_ret))
ret['changes'][func] = func_ret
except (SaltInvocationError, TypeError) as ex:
failures.append("'{0}' failed: {1}".format(func, ex))
ret['comment'] = ', '.join(failures + success)
ret['result'] = not bool(failures)
return ret | [
"def",
"run",
"(",
"*",
"*",
"kwargs",
")",
":",
"if",
"'name'",
"in",
"kwargs",
":",
"kwargs",
".",
"pop",
"(",
"'name'",
")",
"ret",
"=",
"{",
"'name'",
":",
"list",
"(",
"kwargs",
")",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
... | Run a single module function or a range of module functions in a batch.
Supersedes ``module.run`` function, which requires ``m_`` prefix to
function-specific parameters.
:param returner:
Specify a common returner for the whole batch to send the return data
:param kwargs:
Pass any arguments needed to execute the function(s)
.. code-block:: yaml
some_id_of_state:
module.run:
- network.ip_addrs:
- interface: eth0
- cloud.create:
- names:
- test-isbm-1
- test-isbm-2
- ssh_username: sles
- image: sles12sp2
- securitygroup: default
- size: 'c3.large'
- location: ap-northeast-1
- delvol_on_destroy: True
:return: | [
"Run",
"a",
"single",
"module",
"function",
"or",
"a",
"range",
"of",
"module",
"functions",
"in",
"a",
"batch",
".",
"Supersedes",
"module",
".",
"run",
"function",
"which",
"requires",
"m_",
"prefix",
"to",
"function",
"-",
"specific",
"parameters",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/module.py#L350-L436 | train |
saltstack/salt | salt/states/module.py | _call_function | def _call_function(name, returner=None, **kwargs):
'''
Calls a function from the specified module.
:param name:
:param kwargs:
:return:
'''
argspec = salt.utils.args.get_function_argspec(__salt__[name])
# func_kw is initialized to a dictionary of keyword arguments the function to be run accepts
func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):], # pylint: disable=incompatible-py3-code
argspec.defaults or []))
# func_args is initialized to a list of positional arguments that the function to be run accepts
func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])]
arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False
for funcset in reversed(kwargs.get('func_args') or []):
if not isinstance(funcset, dict):
# We are just receiving a list of args to the function to be run, so just append
# those to the arg list that we will pass to the func.
arg_type.append(funcset)
else:
for kwarg_key in six.iterkeys(funcset):
# We are going to pass in a keyword argument. The trick here is to make certain
# that if we find that in the *args* list that we pass it there and not as a kwarg
if kwarg_key in func_args:
kw_to_arg_type[kwarg_key] = funcset[kwarg_key]
continue
else:
# Otherwise, we're good and just go ahead and pass the keyword/value pair into
# the kwargs list to be run.
func_kw.update(funcset)
arg_type.reverse()
for arg in func_args:
if arg in kw_to_arg_type:
arg_type.append(kw_to_arg_type[arg])
_exp_prm = len(argspec.args or []) - len(argspec.defaults or [])
_passed_prm = len(arg_type)
missing = []
if na_type and _exp_prm > _passed_prm:
for arg in argspec.args:
if arg not in func_kw:
missing.append(arg)
if missing:
raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing)))
elif _exp_prm > _passed_prm:
raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format(
_exp_prm, _passed_prm))
mret = __salt__[name](*arg_type, **func_kw)
if returner is not None:
returners = salt.loader.returners(__opts__, __salt__)
if returner in returners:
returners[returner]({'id': __opts__['id'], 'ret': mret,
'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)})
return mret | python | def _call_function(name, returner=None, **kwargs):
'''
Calls a function from the specified module.
:param name:
:param kwargs:
:return:
'''
argspec = salt.utils.args.get_function_argspec(__salt__[name])
# func_kw is initialized to a dictionary of keyword arguments the function to be run accepts
func_kw = dict(zip(argspec.args[-len(argspec.defaults or []):], # pylint: disable=incompatible-py3-code
argspec.defaults or []))
# func_args is initialized to a list of positional arguments that the function to be run accepts
func_args = argspec.args[:len(argspec.args or []) - len(argspec.defaults or [])]
arg_type, kw_to_arg_type, na_type, kw_type = [], {}, {}, False
for funcset in reversed(kwargs.get('func_args') or []):
if not isinstance(funcset, dict):
# We are just receiving a list of args to the function to be run, so just append
# those to the arg list that we will pass to the func.
arg_type.append(funcset)
else:
for kwarg_key in six.iterkeys(funcset):
# We are going to pass in a keyword argument. The trick here is to make certain
# that if we find that in the *args* list that we pass it there and not as a kwarg
if kwarg_key in func_args:
kw_to_arg_type[kwarg_key] = funcset[kwarg_key]
continue
else:
# Otherwise, we're good and just go ahead and pass the keyword/value pair into
# the kwargs list to be run.
func_kw.update(funcset)
arg_type.reverse()
for arg in func_args:
if arg in kw_to_arg_type:
arg_type.append(kw_to_arg_type[arg])
_exp_prm = len(argspec.args or []) - len(argspec.defaults or [])
_passed_prm = len(arg_type)
missing = []
if na_type and _exp_prm > _passed_prm:
for arg in argspec.args:
if arg not in func_kw:
missing.append(arg)
if missing:
raise SaltInvocationError('Missing arguments: {0}'.format(', '.join(missing)))
elif _exp_prm > _passed_prm:
raise SaltInvocationError('Function expects {0} parameters, got only {1}'.format(
_exp_prm, _passed_prm))
mret = __salt__[name](*arg_type, **func_kw)
if returner is not None:
returners = salt.loader.returners(__opts__, __salt__)
if returner in returners:
returners[returner]({'id': __opts__['id'], 'ret': mret,
'fun': name, 'jid': salt.utils.jid.gen_jid(__opts__)})
return mret | [
"def",
"_call_function",
"(",
"name",
",",
"returner",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"argspec",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"get_function_argspec",
"(",
"__salt__",
"[",
"name",
"]",
")",
"# func_kw is initialized to a dict... | Calls a function from the specified module.
:param name:
:param kwargs:
:return: | [
"Calls",
"a",
"function",
"from",
"the",
"specified",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/module.py#L439-L496 | train |
saltstack/salt | salt/states/module.py | _run | def _run(name, **kwargs):
'''
.. deprecated:: 2017.7.0
Function name stays the same, behaviour will change.
Run a single module function
``name``
The module function to execute
``returner``
Specify the returner to send the return of the module execution to
``kwargs``
Pass any arguments needed to execute the function
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
if name not in __salt__:
ret['comment'] = 'Module function {0} is not available'.format(name)
ret['result'] = False
return ret
if __opts__['test']:
ret['comment'] = 'Module function {0} is set to execute'.format(name)
return ret
aspec = salt.utils.args.get_function_argspec(__salt__[name])
args = []
defaults = {}
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
# Match up the defaults with the respective args
for ind in range(arglen - 1, -1, -1):
minus = arglen - ind
if deflen - minus > -1:
defaults[aspec.args[ind]] = aspec.defaults[-minus]
# overwrite passed default kwargs
for arg in defaults:
if arg == 'name':
if 'm_name' in kwargs:
defaults[arg] = kwargs.pop('m_name')
elif arg == 'fun':
if 'm_fun' in kwargs:
defaults[arg] = kwargs.pop('m_fun')
elif arg == 'state':
if 'm_state' in kwargs:
defaults[arg] = kwargs.pop('m_state')
elif arg == 'saltenv':
if 'm_saltenv' in kwargs:
defaults[arg] = kwargs.pop('m_saltenv')
if arg in kwargs:
defaults[arg] = kwargs.pop(arg)
missing = set()
for arg in aspec.args:
if arg == 'name':
rarg = 'm_name'
elif arg == 'fun':
rarg = 'm_fun'
elif arg == 'names':
rarg = 'm_names'
elif arg == 'state':
rarg = 'm_state'
elif arg == 'saltenv':
rarg = 'm_saltenv'
else:
rarg = arg
if rarg not in kwargs and arg not in defaults:
missing.add(rarg)
continue
if arg in defaults:
args.append(defaults[arg])
else:
args.append(kwargs.pop(rarg))
if missing:
comment = 'The following arguments are missing:'
for arg in missing:
comment += ' {0}'.format(arg)
ret['comment'] = comment
ret['result'] = False
return ret
if aspec.varargs:
if aspec.varargs == 'name':
rarg = 'm_name'
elif aspec.varargs == 'fun':
rarg = 'm_fun'
elif aspec.varargs == 'names':
rarg = 'm_names'
elif aspec.varargs == 'state':
rarg = 'm_state'
elif aspec.varargs == 'saltenv':
rarg = 'm_saltenv'
else:
rarg = aspec.varargs
if rarg in kwargs:
varargs = kwargs.pop(rarg)
if not isinstance(varargs, list):
msg = "'{0}' must be a list."
ret['comment'] = msg.format(aspec.varargs)
ret['result'] = False
return ret
args.extend(varargs)
nkwargs = {}
if aspec.keywords and aspec.keywords in kwargs:
nkwargs = kwargs.pop(aspec.keywords)
if not isinstance(nkwargs, dict):
msg = "'{0}' must be a dict."
ret['comment'] = msg.format(aspec.keywords)
ret['result'] = False
return ret
try:
if aspec.keywords:
mret = __salt__[name](*args, **nkwargs)
else:
mret = __salt__[name](*args)
except Exception as e:
ret['comment'] = 'Module function {0} threw an exception. Exception: {1}'.format(name, e)
ret['result'] = False
return ret
else:
if mret is not None or mret is not {}:
ret['changes']['ret'] = mret
if 'returner' in kwargs:
ret_ret = {
'id': __opts__['id'],
'ret': mret,
'fun': name,
'jid': salt.utils.jid.gen_jid(__opts__)}
returners = salt.loader.returners(__opts__, __salt__)
if kwargs['returner'] in returners:
returners[kwargs['returner']](ret_ret)
ret['comment'] = 'Module function {0} executed'.format(name)
ret['result'] = _get_result(mret, ret['changes'])
return ret | python | def _run(name, **kwargs):
'''
.. deprecated:: 2017.7.0
Function name stays the same, behaviour will change.
Run a single module function
``name``
The module function to execute
``returner``
Specify the returner to send the return of the module execution to
``kwargs``
Pass any arguments needed to execute the function
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': None}
if name not in __salt__:
ret['comment'] = 'Module function {0} is not available'.format(name)
ret['result'] = False
return ret
if __opts__['test']:
ret['comment'] = 'Module function {0} is set to execute'.format(name)
return ret
aspec = salt.utils.args.get_function_argspec(__salt__[name])
args = []
defaults = {}
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
# Match up the defaults with the respective args
for ind in range(arglen - 1, -1, -1):
minus = arglen - ind
if deflen - minus > -1:
defaults[aspec.args[ind]] = aspec.defaults[-minus]
# overwrite passed default kwargs
for arg in defaults:
if arg == 'name':
if 'm_name' in kwargs:
defaults[arg] = kwargs.pop('m_name')
elif arg == 'fun':
if 'm_fun' in kwargs:
defaults[arg] = kwargs.pop('m_fun')
elif arg == 'state':
if 'm_state' in kwargs:
defaults[arg] = kwargs.pop('m_state')
elif arg == 'saltenv':
if 'm_saltenv' in kwargs:
defaults[arg] = kwargs.pop('m_saltenv')
if arg in kwargs:
defaults[arg] = kwargs.pop(arg)
missing = set()
for arg in aspec.args:
if arg == 'name':
rarg = 'm_name'
elif arg == 'fun':
rarg = 'm_fun'
elif arg == 'names':
rarg = 'm_names'
elif arg == 'state':
rarg = 'm_state'
elif arg == 'saltenv':
rarg = 'm_saltenv'
else:
rarg = arg
if rarg not in kwargs and arg not in defaults:
missing.add(rarg)
continue
if arg in defaults:
args.append(defaults[arg])
else:
args.append(kwargs.pop(rarg))
if missing:
comment = 'The following arguments are missing:'
for arg in missing:
comment += ' {0}'.format(arg)
ret['comment'] = comment
ret['result'] = False
return ret
if aspec.varargs:
if aspec.varargs == 'name':
rarg = 'm_name'
elif aspec.varargs == 'fun':
rarg = 'm_fun'
elif aspec.varargs == 'names':
rarg = 'm_names'
elif aspec.varargs == 'state':
rarg = 'm_state'
elif aspec.varargs == 'saltenv':
rarg = 'm_saltenv'
else:
rarg = aspec.varargs
if rarg in kwargs:
varargs = kwargs.pop(rarg)
if not isinstance(varargs, list):
msg = "'{0}' must be a list."
ret['comment'] = msg.format(aspec.varargs)
ret['result'] = False
return ret
args.extend(varargs)
nkwargs = {}
if aspec.keywords and aspec.keywords in kwargs:
nkwargs = kwargs.pop(aspec.keywords)
if not isinstance(nkwargs, dict):
msg = "'{0}' must be a dict."
ret['comment'] = msg.format(aspec.keywords)
ret['result'] = False
return ret
try:
if aspec.keywords:
mret = __salt__[name](*args, **nkwargs)
else:
mret = __salt__[name](*args)
except Exception as e:
ret['comment'] = 'Module function {0} threw an exception. Exception: {1}'.format(name, e)
ret['result'] = False
return ret
else:
if mret is not None or mret is not {}:
ret['changes']['ret'] = mret
if 'returner' in kwargs:
ret_ret = {
'id': __opts__['id'],
'ret': mret,
'fun': name,
'jid': salt.utils.jid.gen_jid(__opts__)}
returners = salt.loader.returners(__opts__, __salt__)
if kwargs['returner'] in returners:
returners[kwargs['returner']](ret_ret)
ret['comment'] = 'Module function {0} executed'.format(name)
ret['result'] = _get_result(mret, ret['changes'])
return ret | [
"def",
"_run",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'result'",
":",
"None",
"}",
"if",
"name",
"not",
"in",
"__salt__",
":",
... | .. deprecated:: 2017.7.0
Function name stays the same, behaviour will change.
Run a single module function
``name``
The module function to execute
``returner``
Specify the returner to send the return of the module execution to
``kwargs``
Pass any arguments needed to execute the function | [
"..",
"deprecated",
"::",
"2017",
".",
"7",
".",
"0",
"Function",
"name",
"stays",
"the",
"same",
"behaviour",
"will",
"change",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/module.py#L499-L647 | train |
saltstack/salt | salt/matchers/list_match.py | match | def match(tgt, opts=None):
'''
Determines if this host is on the list
'''
if not opts:
opts = __opts__
try:
if ',' + opts['id'] + ',' in tgt \
or tgt.startswith(opts['id'] + ',') \
or tgt.endswith(',' + opts['id']):
return True
# tgt is a string, which we know because the if statement above did not
# cause one of the exceptions being caught. Therefore, look for an
# exact match. (e.g. salt -L foo test.ping)
return opts['id'] == tgt
except (AttributeError, TypeError):
# tgt is not a string, maybe it's a sequence type?
try:
return opts['id'] in tgt
except Exception:
# tgt was likely some invalid type
return False
# We should never get here based on the return statements in the logic
# above. If we do, it is because something above changed, and should be
# considered as a bug. Log a warning to help us catch this.
log.warning(
'List matcher unexpectedly did not return, for target %s, '
'this is probably a bug.', tgt
)
return False | python | def match(tgt, opts=None):
'''
Determines if this host is on the list
'''
if not opts:
opts = __opts__
try:
if ',' + opts['id'] + ',' in tgt \
or tgt.startswith(opts['id'] + ',') \
or tgt.endswith(',' + opts['id']):
return True
# tgt is a string, which we know because the if statement above did not
# cause one of the exceptions being caught. Therefore, look for an
# exact match. (e.g. salt -L foo test.ping)
return opts['id'] == tgt
except (AttributeError, TypeError):
# tgt is not a string, maybe it's a sequence type?
try:
return opts['id'] in tgt
except Exception:
# tgt was likely some invalid type
return False
# We should never get here based on the return statements in the logic
# above. If we do, it is because something above changed, and should be
# considered as a bug. Log a warning to help us catch this.
log.warning(
'List matcher unexpectedly did not return, for target %s, '
'this is probably a bug.', tgt
)
return False | [
"def",
"match",
"(",
"tgt",
",",
"opts",
"=",
"None",
")",
":",
"if",
"not",
"opts",
":",
"opts",
"=",
"__opts__",
"try",
":",
"if",
"','",
"+",
"opts",
"[",
"'id'",
"]",
"+",
"','",
"in",
"tgt",
"or",
"tgt",
".",
"startswith",
"(",
"opts",
"["... | Determines if this host is on the list | [
"Determines",
"if",
"this",
"host",
"is",
"on",
"the",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/list_match.py#L11-L42 | train |
saltstack/salt | salt/modules/influxdb08mod.py | db_list | def db_list(user=None, password=None, host=None, port=None):
'''
List all InfluxDB databases
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_list
salt '*' influxdb08.db_list <user> <password> <host> <port>
'''
client = _client(user=user, password=password, host=host, port=port)
return client.get_list_database() | python | def db_list(user=None, password=None, host=None, port=None):
'''
List all InfluxDB databases
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_list
salt '*' influxdb08.db_list <user> <password> <host> <port>
'''
client = _client(user=user, password=password, host=host, port=port)
return client.get_list_database() | [
"def",
"db_list",
"(",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"client",
"=",
"_client",
"(",
"user",
"=",
"user",
",",
"password",
"=",
"password",
",",
"host",
"=",
"host",
... | List all InfluxDB databases
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_list
salt '*' influxdb08.db_list <user> <password> <host> <port> | [
"List",
"all",
"InfluxDB",
"databases"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L65-L90 | train |
saltstack/salt | salt/modules/influxdb08mod.py | db_exists | def db_exists(name, user=None, password=None, host=None, port=None):
'''
Checks if a database exists in Influxdb
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_exists <name>
salt '*' influxdb08.db_exists <name> <user> <password> <host> <port>
'''
dbs = db_list(user, password, host, port)
if not isinstance(dbs, list):
return False
return name in [db['name'] for db in dbs] | python | def db_exists(name, user=None, password=None, host=None, port=None):
'''
Checks if a database exists in Influxdb
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_exists <name>
salt '*' influxdb08.db_exists <name> <user> <password> <host> <port>
'''
dbs = db_list(user, password, host, port)
if not isinstance(dbs, list):
return False
return name in [db['name'] for db in dbs] | [
"def",
"db_exists",
"(",
"name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"dbs",
"=",
"db_list",
"(",
"user",
",",
"password",
",",
"host",
",",
"port",
")",
"if",
"not"... | Checks if a database exists in Influxdb
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_exists <name>
salt '*' influxdb08.db_exists <name> <user> <password> <host> <port> | [
"Checks",
"if",
"a",
"database",
"exists",
"in",
"Influxdb"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L93-L122 | train |
saltstack/salt | salt/modules/influxdb08mod.py | db_create | def db_create(name, user=None, password=None, host=None, port=None):
'''
Create a database
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_create <name>
salt '*' influxdb08.db_create <name> <user> <password> <host> <port>
'''
if db_exists(name, user, password, host, port):
log.info('DB \'%s\' already exists', name)
return False
client = _client(user=user, password=password, host=host, port=port)
client.create_database(name)
return True | python | def db_create(name, user=None, password=None, host=None, port=None):
'''
Create a database
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_create <name>
salt '*' influxdb08.db_create <name> <user> <password> <host> <port>
'''
if db_exists(name, user, password, host, port):
log.info('DB \'%s\' already exists', name)
return False
client = _client(user=user, password=password, host=host, port=port)
client.create_database(name)
return True | [
"def",
"db_create",
"(",
"name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"db_exists",
"(",
"name",
",",
"user",
",",
"password",
",",
"host",
",",
"port",
")",
":... | Create a database
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_create <name>
salt '*' influxdb08.db_create <name> <user> <password> <host> <port> | [
"Create",
"a",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L125-L156 | train |
saltstack/salt | salt/modules/influxdb08mod.py | db_remove | def db_remove(name, user=None, password=None, host=None, port=None):
'''
Remove a database
name
Database name to remove
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_remove <name>
salt '*' influxdb08.db_remove <name> <user> <password> <host> <port>
'''
if not db_exists(name, user, password, host, port):
log.info('DB \'%s\' does not exist', name)
return False
client = _client(user=user, password=password, host=host, port=port)
return client.delete_database(name) | python | def db_remove(name, user=None, password=None, host=None, port=None):
'''
Remove a database
name
Database name to remove
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_remove <name>
salt '*' influxdb08.db_remove <name> <user> <password> <host> <port>
'''
if not db_exists(name, user, password, host, port):
log.info('DB \'%s\' does not exist', name)
return False
client = _client(user=user, password=password, host=host, port=port)
return client.delete_database(name) | [
"def",
"db_remove",
"(",
"name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"not",
"db_exists",
"(",
"name",
",",
"user",
",",
"password",
",",
"host",
",",
"port",
... | Remove a database
name
Database name to remove
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.db_remove <name>
salt '*' influxdb08.db_remove <name> <user> <password> <host> <port> | [
"Remove",
"a",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L159-L189 | train |
saltstack/salt | salt/modules/influxdb08mod.py | user_list | def user_list(database=None, user=None, password=None, host=None, port=None):
'''
List cluster admins or database users.
If a database is specified: it will return database users list.
If a database is not specified: it will return cluster admins list.
database
The database to list the users from
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_list
salt '*' influxdb08.user_list <database>
salt '*' influxdb08.user_list <database> <user> <password> <host> <port>
'''
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.get_list_cluster_admins()
client.switch_database(database)
return client.get_list_users() | python | def user_list(database=None, user=None, password=None, host=None, port=None):
'''
List cluster admins or database users.
If a database is specified: it will return database users list.
If a database is not specified: it will return cluster admins list.
database
The database to list the users from
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_list
salt '*' influxdb08.user_list <database>
salt '*' influxdb08.user_list <database> <user> <password> <host> <port>
'''
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.get_list_cluster_admins()
client.switch_database(database)
return client.get_list_users() | [
"def",
"user_list",
"(",
"database",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"client",
"=",
"_client",
"(",
"user",
"=",
"user",
",",
"password",
"=",
"passw... | List cluster admins or database users.
If a database is specified: it will return database users list.
If a database is not specified: it will return cluster admins list.
database
The database to list the users from
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_list
salt '*' influxdb08.user_list <database>
salt '*' influxdb08.user_list <database> <user> <password> <host> <port> | [
"List",
"cluster",
"admins",
"or",
"database",
"users",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L192-L228 | train |
saltstack/salt | salt/modules/influxdb08mod.py | user_exists | def user_exists(name, database=None, user=None, password=None, host=None, port=None):
'''
Checks if a cluster admin or database user exists.
If a database is specified: it will check for database user existence.
If a database is not specified: it will check for cluster admin existence.
name
User name
database
The database to check for the user to exist
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_exists <name>
salt '*' influxdb08.user_exists <name> <database>
salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port>
'''
users = user_list(database, user, password, host, port)
if not isinstance(users, list):
return False
for user in users:
# the dict key could be different depending on influxdb version
username = user.get('user', user.get('name'))
if username:
if username == name:
return True
else:
log.warning('Could not find username in user: %s', user)
return False | python | def user_exists(name, database=None, user=None, password=None, host=None, port=None):
'''
Checks if a cluster admin or database user exists.
If a database is specified: it will check for database user existence.
If a database is not specified: it will check for cluster admin existence.
name
User name
database
The database to check for the user to exist
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_exists <name>
salt '*' influxdb08.user_exists <name> <database>
salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port>
'''
users = user_list(database, user, password, host, port)
if not isinstance(users, list):
return False
for user in users:
# the dict key could be different depending on influxdb version
username = user.get('user', user.get('name'))
if username:
if username == name:
return True
else:
log.warning('Could not find username in user: %s', user)
return False | [
"def",
"user_exists",
"(",
"name",
",",
"database",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"users",
"=",
"user_list",
"(",
"database",
",",
"user",
",",
"pa... | Checks if a cluster admin or database user exists.
If a database is specified: it will check for database user existence.
If a database is not specified: it will check for cluster admin existence.
name
User name
database
The database to check for the user to exist
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_exists <name>
salt '*' influxdb08.user_exists <name> <database>
salt '*' influxdb08.user_exists <name> <database> <user> <password> <host> <port> | [
"Checks",
"if",
"a",
"cluster",
"admin",
"or",
"database",
"user",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L231-L277 | train |
saltstack/salt | salt/modules/influxdb08mod.py | user_create | def user_create(name,
passwd,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Create a cluster admin or a database user.
If a database is specified: it will create database user.
If a database is not specified: it will create a cluster admin.
name
User name for the new user to create
passwd
Password for the new user to create
database
The database to create the user in
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_create <name> <passwd>
salt '*' influxdb08.user_create <name> <passwd> <database>
salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port>
'''
if user_exists(name, database, user, password, host, port):
if database:
log.info('User \'%s\' already exists for DB \'%s\'', name, database)
else:
log.info('Cluster admin \'%s\' already exists', name)
return False
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.add_cluster_admin(name, passwd)
client.switch_database(database)
return client.add_database_user(name, passwd) | python | def user_create(name,
passwd,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Create a cluster admin or a database user.
If a database is specified: it will create database user.
If a database is not specified: it will create a cluster admin.
name
User name for the new user to create
passwd
Password for the new user to create
database
The database to create the user in
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_create <name> <passwd>
salt '*' influxdb08.user_create <name> <passwd> <database>
salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port>
'''
if user_exists(name, database, user, password, host, port):
if database:
log.info('User \'%s\' already exists for DB \'%s\'', name, database)
else:
log.info('Cluster admin \'%s\' already exists', name)
return False
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.add_cluster_admin(name, passwd)
client.switch_database(database)
return client.add_database_user(name, passwd) | [
"def",
"user_create",
"(",
"name",
",",
"passwd",
",",
"database",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"user_exists",
"(",
"name",
",",
"database",
... | Create a cluster admin or a database user.
If a database is specified: it will create database user.
If a database is not specified: it will create a cluster admin.
name
User name for the new user to create
passwd
Password for the new user to create
database
The database to create the user in
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_create <name> <passwd>
salt '*' influxdb08.user_create <name> <passwd> <database>
salt '*' influxdb08.user_create <name> <passwd> <database> <user> <password> <host> <port> | [
"Create",
"a",
"cluster",
"admin",
"or",
"a",
"database",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L280-L335 | train |
saltstack/salt | salt/modules/influxdb08mod.py | user_chpass | def user_chpass(name,
passwd,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Change password for a cluster admin or a database user.
If a database is specified: it will update database user password.
If a database is not specified: it will update cluster admin password.
name
User name for whom to change the password
passwd
New password
database
The database on which to operate
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_chpass <name> <passwd>
salt '*' influxdb08.user_chpass <name> <passwd> <database>
salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port>
'''
if not user_exists(name, database, user, password, host, port):
if database:
log.info('User \'%s\' does not exist for DB \'%s\'', name, database)
else:
log.info('Cluster admin \'%s\' does not exist', name)
return False
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.update_cluster_admin_password(name, passwd)
client.switch_database(database)
return client.update_database_user_password(name, passwd) | python | def user_chpass(name,
passwd,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Change password for a cluster admin or a database user.
If a database is specified: it will update database user password.
If a database is not specified: it will update cluster admin password.
name
User name for whom to change the password
passwd
New password
database
The database on which to operate
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_chpass <name> <passwd>
salt '*' influxdb08.user_chpass <name> <passwd> <database>
salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port>
'''
if not user_exists(name, database, user, password, host, port):
if database:
log.info('User \'%s\' does not exist for DB \'%s\'', name, database)
else:
log.info('Cluster admin \'%s\' does not exist', name)
return False
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.update_cluster_admin_password(name, passwd)
client.switch_database(database)
return client.update_database_user_password(name, passwd) | [
"def",
"user_chpass",
"(",
"name",
",",
"passwd",
",",
"database",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"not",
"user_exists",
"(",
"name",
",",
"dat... | Change password for a cluster admin or a database user.
If a database is specified: it will update database user password.
If a database is not specified: it will update cluster admin password.
name
User name for whom to change the password
passwd
New password
database
The database on which to operate
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_chpass <name> <passwd>
salt '*' influxdb08.user_chpass <name> <passwd> <database>
salt '*' influxdb08.user_chpass <name> <passwd> <database> <user> <password> <host> <port> | [
"Change",
"password",
"for",
"a",
"cluster",
"admin",
"or",
"a",
"database",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L338-L393 | train |
saltstack/salt | salt/modules/influxdb08mod.py | user_remove | def user_remove(name,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Remove a cluster admin or a database user.
If a database is specified: it will remove the database user.
If a database is not specified: it will remove the cluster admin.
name
User name to remove
database
The database to remove the user from
user
User name for the new user to delete
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_remove <name>
salt '*' influxdb08.user_remove <name> <database>
salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port>
'''
if not user_exists(name, database, user, password, host, port):
if database:
log.info('User \'%s\' does not exist for DB \'%s\'', name, database)
else:
log.info('Cluster admin \'%s\' does not exist', name)
return False
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.delete_cluster_admin(name)
client.switch_database(database)
return client.delete_database_user(name) | python | def user_remove(name,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Remove a cluster admin or a database user.
If a database is specified: it will remove the database user.
If a database is not specified: it will remove the cluster admin.
name
User name to remove
database
The database to remove the user from
user
User name for the new user to delete
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_remove <name>
salt '*' influxdb08.user_remove <name> <database>
salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port>
'''
if not user_exists(name, database, user, password, host, port):
if database:
log.info('User \'%s\' does not exist for DB \'%s\'', name, database)
else:
log.info('Cluster admin \'%s\' does not exist', name)
return False
client = _client(user=user, password=password, host=host, port=port)
if not database:
return client.delete_cluster_admin(name)
client.switch_database(database)
return client.delete_database_user(name) | [
"def",
"user_remove",
"(",
"name",
",",
"database",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"not",
"user_exists",
"(",
"name",
",",
"database",
",",
"u... | Remove a cluster admin or a database user.
If a database is specified: it will remove the database user.
If a database is not specified: it will remove the cluster admin.
name
User name to remove
database
The database to remove the user from
user
User name for the new user to delete
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.user_remove <name>
salt '*' influxdb08.user_remove <name> <database>
salt '*' influxdb08.user_remove <name> <database> <user> <password> <host> <port> | [
"Remove",
"a",
"cluster",
"admin",
"or",
"a",
"database",
"user",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L396-L450 | train |
saltstack/salt | salt/modules/influxdb08mod.py | retention_policy_get | def retention_policy_get(database,
name,
user=None,
password=None,
host=None,
port=None):
'''
Get an existing retention policy.
database
The database to operate on.
name
Name of the policy to modify.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_get metrics default
'''
client = _client(user=user, password=password, host=host, port=port)
for policy in client.get_list_retention_policies(database):
if policy['name'] == name:
return policy
return None | python | def retention_policy_get(database,
name,
user=None,
password=None,
host=None,
port=None):
'''
Get an existing retention policy.
database
The database to operate on.
name
Name of the policy to modify.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_get metrics default
'''
client = _client(user=user, password=password, host=host, port=port)
for policy in client.get_list_retention_policies(database):
if policy['name'] == name:
return policy
return None | [
"def",
"retention_policy_get",
"(",
"database",
",",
"name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"client",
"=",
"_client",
"(",
"user",
"=",
"user",
",",
"password",
"=... | Get an existing retention policy.
database
The database to operate on.
name
Name of the policy to modify.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_get metrics default | [
"Get",
"an",
"existing",
"retention",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L453-L480 | train |
saltstack/salt | salt/modules/influxdb08mod.py | retention_policy_exists | def retention_policy_exists(database,
name,
user=None,
password=None,
host=None,
port=None):
'''
Check if a retention policy exists.
database
The database to operate on.
name
Name of the policy to modify.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_exists metrics default
'''
policy = retention_policy_get(database, name, user, password, host, port)
return policy is not None | python | def retention_policy_exists(database,
name,
user=None,
password=None,
host=None,
port=None):
'''
Check if a retention policy exists.
database
The database to operate on.
name
Name of the policy to modify.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_exists metrics default
'''
policy = retention_policy_get(database, name, user, password, host, port)
return policy is not None | [
"def",
"retention_policy_exists",
"(",
"database",
",",
"name",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"policy",
"=",
"retention_policy_get",
"(",
"database",
",",
"name",
","... | Check if a retention policy exists.
database
The database to operate on.
name
Name of the policy to modify.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_exists metrics default | [
"Check",
"if",
"a",
"retention",
"policy",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L483-L505 | train |
saltstack/salt | salt/modules/influxdb08mod.py | retention_policy_add | def retention_policy_add(database,
name,
duration,
replication,
default=False,
user=None,
password=None,
host=None,
port=None):
'''
Add a retention policy.
database
The database to operate on.
name
Name of the policy to modify.
duration
How long InfluxDB keeps the data.
replication
How many copies of the data are stored in the cluster.
default
Whether this policy should be the default or not. Default is False.
CLI Example:
.. code-block:: bash
salt '*' influxdb.retention_policy_add metrics default 1d 1
'''
client = _client(user=user, password=password, host=host, port=port)
client.create_retention_policy(name, duration, replication, database, default)
return True | python | def retention_policy_add(database,
name,
duration,
replication,
default=False,
user=None,
password=None,
host=None,
port=None):
'''
Add a retention policy.
database
The database to operate on.
name
Name of the policy to modify.
duration
How long InfluxDB keeps the data.
replication
How many copies of the data are stored in the cluster.
default
Whether this policy should be the default or not. Default is False.
CLI Example:
.. code-block:: bash
salt '*' influxdb.retention_policy_add metrics default 1d 1
'''
client = _client(user=user, password=password, host=host, port=port)
client.create_retention_policy(name, duration, replication, database, default)
return True | [
"def",
"retention_policy_add",
"(",
"database",
",",
"name",
",",
"duration",
",",
"replication",
",",
"default",
"=",
"False",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"clien... | Add a retention policy.
database
The database to operate on.
name
Name of the policy to modify.
duration
How long InfluxDB keeps the data.
replication
How many copies of the data are stored in the cluster.
default
Whether this policy should be the default or not. Default is False.
CLI Example:
.. code-block:: bash
salt '*' influxdb.retention_policy_add metrics default 1d 1 | [
"Add",
"a",
"retention",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L508-L543 | train |
saltstack/salt | salt/modules/influxdb08mod.py | retention_policy_alter | def retention_policy_alter(database,
name,
duration,
replication,
default=False,
user=None,
password=None,
host=None,
port=None):
'''
Modify an existing retention policy.
database
The database to operate on.
name
Name of the policy to modify.
duration
How long InfluxDB keeps the data.
replication
How many copies of the data are stored in the cluster.
default
Whether this policy should be the default or not. Default is False.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_modify metrics default 1d 1
'''
client = _client(user=user, password=password, host=host, port=port)
client.alter_retention_policy(name, database, duration, replication, default)
return True | python | def retention_policy_alter(database,
name,
duration,
replication,
default=False,
user=None,
password=None,
host=None,
port=None):
'''
Modify an existing retention policy.
database
The database to operate on.
name
Name of the policy to modify.
duration
How long InfluxDB keeps the data.
replication
How many copies of the data are stored in the cluster.
default
Whether this policy should be the default or not. Default is False.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_modify metrics default 1d 1
'''
client = _client(user=user, password=password, host=host, port=port)
client.alter_retention_policy(name, database, duration, replication, default)
return True | [
"def",
"retention_policy_alter",
"(",
"database",
",",
"name",
",",
"duration",
",",
"replication",
",",
"default",
"=",
"False",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"cli... | Modify an existing retention policy.
database
The database to operate on.
name
Name of the policy to modify.
duration
How long InfluxDB keeps the data.
replication
How many copies of the data are stored in the cluster.
default
Whether this policy should be the default or not. Default is False.
CLI Example:
.. code-block:: bash
salt '*' influxdb08.retention_policy_modify metrics default 1d 1 | [
"Modify",
"an",
"existing",
"retention",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L546-L581 | train |
saltstack/salt | salt/modules/influxdb08mod.py | query | def query(database,
query,
time_precision='s',
chunked=False,
user=None,
password=None,
host=None,
port=None):
'''
Querying data
database
The database to query
query
Query to be executed
time_precision
Time precision to use ('s', 'm', or 'u')
chunked
Whether is chunked or not
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.query <database> <query>
salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port>
'''
client = _client(user=user, password=password, host=host, port=port)
client.switch_database(database)
return client.query(query, time_precision=time_precision, chunked=chunked) | python | def query(database,
query,
time_precision='s',
chunked=False,
user=None,
password=None,
host=None,
port=None):
'''
Querying data
database
The database to query
query
Query to be executed
time_precision
Time precision to use ('s', 'm', or 'u')
chunked
Whether is chunked or not
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.query <database> <query>
salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port>
'''
client = _client(user=user, password=password, host=host, port=port)
client.switch_database(database)
return client.query(query, time_precision=time_precision, chunked=chunked) | [
"def",
"query",
"(",
"database",
",",
"query",
",",
"time_precision",
"=",
"'s'",
",",
"chunked",
"=",
"False",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"client",
"=",
"_c... | Querying data
database
The database to query
query
Query to be executed
time_precision
Time precision to use ('s', 'm', or 'u')
chunked
Whether is chunked or not
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influxdb08.query <database> <query>
salt '*' influxdb08.query <database> <query> <time_precision> <chunked> <user> <password> <host> <port> | [
"Querying",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/influxdb08mod.py#L584-L628 | train |
saltstack/salt | salt/log/handlers/__init__.py | TemporaryLoggingHandler.sync_with_handlers | def sync_with_handlers(self, handlers=()):
'''
Sync the stored log records to the provided log handlers.
'''
if not handlers:
return
while self.__messages:
record = self.__messages.pop(0)
for handler in handlers:
if handler.level > record.levelno:
# If the handler's level is higher than the log record one,
# it should not handle the log record
continue
handler.handle(record) | python | def sync_with_handlers(self, handlers=()):
'''
Sync the stored log records to the provided log handlers.
'''
if not handlers:
return
while self.__messages:
record = self.__messages.pop(0)
for handler in handlers:
if handler.level > record.levelno:
# If the handler's level is higher than the log record one,
# it should not handle the log record
continue
handler.handle(record) | [
"def",
"sync_with_handlers",
"(",
"self",
",",
"handlers",
"=",
"(",
")",
")",
":",
"if",
"not",
"handlers",
":",
"return",
"while",
"self",
".",
"__messages",
":",
"record",
"=",
"self",
".",
"__messages",
".",
"pop",
"(",
"0",
")",
"for",
"handler",
... | Sync the stored log records to the provided log handlers. | [
"Sync",
"the",
"stored",
"log",
"records",
"to",
"the",
"provided",
"log",
"handlers",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/__init__.py#L73-L87 | train |
saltstack/salt | salt/log/handlers/__init__.py | SysLogHandler.handleError | def handleError(self, record):
'''
Override the default error handling mechanism for py3
Deal with syslog os errors when the log file does not exist
'''
handled = False
if sys.stderr and sys.version_info >= (3, 5, 4):
t, v, tb = sys.exc_info()
if t.__name__ in 'FileNotFoundError':
sys.stderr.write('[WARNING ] The log_file does not exist. Logging not setup correctly or syslog service not started.\n')
handled = True
if not handled:
super(SysLogHandler, self).handleError(record) | python | def handleError(self, record):
'''
Override the default error handling mechanism for py3
Deal with syslog os errors when the log file does not exist
'''
handled = False
if sys.stderr and sys.version_info >= (3, 5, 4):
t, v, tb = sys.exc_info()
if t.__name__ in 'FileNotFoundError':
sys.stderr.write('[WARNING ] The log_file does not exist. Logging not setup correctly or syslog service not started.\n')
handled = True
if not handled:
super(SysLogHandler, self).handleError(record) | [
"def",
"handleError",
"(",
"self",
",",
"record",
")",
":",
"handled",
"=",
"False",
"if",
"sys",
".",
"stderr",
"and",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"5",
",",
"4",
")",
":",
"t",
",",
"v",
",",
"tb",
"=",
"sys",
".",
"exc_in... | Override the default error handling mechanism for py3
Deal with syslog os errors when the log file does not exist | [
"Override",
"the",
"default",
"error",
"handling",
"mechanism",
"for",
"py3",
"Deal",
"with",
"syslog",
"os",
"errors",
"when",
"the",
"log",
"file",
"does",
"not",
"exist"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/__init__.py#L106-L119 | train |
saltstack/salt | salt/log/handlers/__init__.py | RotatingFileHandler.handleError | def handleError(self, record):
'''
Override the default error handling mechanism
Deal with log file rotation errors due to log file in use
more softly.
'''
handled = False
# Can't use "salt.utils.platform.is_windows()" in this file
if (sys.platform.startswith('win') and
logging.raiseExceptions and
sys.stderr): # see Python issue 13807
exc_type, exc, exc_traceback = sys.exc_info()
try:
# PermissionError is used since Python 3.3.
# OSError is used for previous versions of Python.
if exc_type.__name__ in ('PermissionError', 'OSError') and exc.winerror == 32:
if self.level <= logging.WARNING:
sys.stderr.write('[WARNING ] Unable to rotate the log file "{0}" '
'because it is in use\n'.format(self.baseFilename)
)
handled = True
finally:
# 'del' recommended. See documentation of
# 'sys.exc_info()' for details.
del exc_type, exc, exc_traceback
if not handled:
super(RotatingFileHandler, self).handleError(record) | python | def handleError(self, record):
'''
Override the default error handling mechanism
Deal with log file rotation errors due to log file in use
more softly.
'''
handled = False
# Can't use "salt.utils.platform.is_windows()" in this file
if (sys.platform.startswith('win') and
logging.raiseExceptions and
sys.stderr): # see Python issue 13807
exc_type, exc, exc_traceback = sys.exc_info()
try:
# PermissionError is used since Python 3.3.
# OSError is used for previous versions of Python.
if exc_type.__name__ in ('PermissionError', 'OSError') and exc.winerror == 32:
if self.level <= logging.WARNING:
sys.stderr.write('[WARNING ] Unable to rotate the log file "{0}" '
'because it is in use\n'.format(self.baseFilename)
)
handled = True
finally:
# 'del' recommended. See documentation of
# 'sys.exc_info()' for details.
del exc_type, exc, exc_traceback
if not handled:
super(RotatingFileHandler, self).handleError(record) | [
"def",
"handleError",
"(",
"self",
",",
"record",
")",
":",
"handled",
"=",
"False",
"# Can't use \"salt.utils.platform.is_windows()\" in this file",
"if",
"(",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
"and",
"logging",
".",
"raiseExceptions",
... | Override the default error handling mechanism
Deal with log file rotation errors due to log file in use
more softly. | [
"Override",
"the",
"default",
"error",
"handling",
"mechanism"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/handlers/__init__.py#L126-L155 | train |
saltstack/salt | salt/beacons/status.py | beacon | def beacon(config):
'''
Return status for requested information
'''
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
if not config:
config = [{
'loadavg': ['all'],
'cpustats': ['all'],
'meminfo': ['all'],
'vmstats': ['all'],
'time': ['all'],
}]
if not isinstance(config, list):
# To support the old dictionary config format
config = [config]
ret = {}
for entry in config:
for func in entry:
ret[func] = {}
try:
data = __salt__['status.{0}'.format(func)]()
except salt.exceptions.CommandExecutionError as exc:
log.debug('Status beacon attempted to process function %s '
'but encountered error: %s', func, exc)
continue
if not isinstance(entry[func], list):
func_items = [entry[func]]
else:
func_items = entry[func]
for item in func_items:
if item == 'all':
ret[func] = data
else:
try:
try:
ret[func][item] = data[item]
except TypeError:
ret[func][item] = data[int(item)]
except KeyError as exc:
ret[func] = 'Status beacon is incorrectly configured: {0}'.format(exc)
return [{
'tag': ctime,
'data': ret,
}] | python | def beacon(config):
'''
Return status for requested information
'''
log.debug(config)
ctime = datetime.datetime.utcnow().isoformat()
if not config:
config = [{
'loadavg': ['all'],
'cpustats': ['all'],
'meminfo': ['all'],
'vmstats': ['all'],
'time': ['all'],
}]
if not isinstance(config, list):
# To support the old dictionary config format
config = [config]
ret = {}
for entry in config:
for func in entry:
ret[func] = {}
try:
data = __salt__['status.{0}'.format(func)]()
except salt.exceptions.CommandExecutionError as exc:
log.debug('Status beacon attempted to process function %s '
'but encountered error: %s', func, exc)
continue
if not isinstance(entry[func], list):
func_items = [entry[func]]
else:
func_items = entry[func]
for item in func_items:
if item == 'all':
ret[func] = data
else:
try:
try:
ret[func][item] = data[item]
except TypeError:
ret[func][item] = data[int(item)]
except KeyError as exc:
ret[func] = 'Status beacon is incorrectly configured: {0}'.format(exc)
return [{
'tag': ctime,
'data': ret,
}] | [
"def",
"beacon",
"(",
"config",
")",
":",
"log",
".",
"debug",
"(",
"config",
")",
"ctime",
"=",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
"if",
"not",
"config",
":",
"config",
"=",
"[",
"{",
"'loadavg'",
":"... | Return status for requested information | [
"Return",
"status",
"for",
"requested",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/status.py#L119-L168 | train |
saltstack/salt | salt/states/sysctl.py | present | def present(name, value, config=None):
'''
Ensure that the named sysctl value is set in memory and persisted to the
named configuration file. The default sysctl configuration file is
/etc/sysctl.conf
name
The name of the sysctl value to edit
value
The sysctl value to apply
config
The location of the sysctl configuration file. If not specified, the
proper location will be detected based on platform.
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if config is None:
# Certain linux systems will ignore /etc/sysctl.conf, get the right
# default configuration file.
if 'sysctl.default_config' in __salt__:
config = __salt__['sysctl.default_config']()
else:
config = '/etc/sysctl.conf'
if __opts__['test']:
current = __salt__['sysctl.show']()
configured = __salt__['sysctl.show'](config_file=config)
if configured is None:
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} might be changed, we failed to check '
'config file at {1}. The file is either unreadable, or '
'missing.'.format(name, config)
)
return ret
if name in current and name not in configured:
if re.sub(' +|\t+', ' ', current[name]) != \
re.sub(' +|\t+', ' ', six.text_type(value)):
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} set to be changed to {1}'
.format(name, value)
)
return ret
else:
ret['result'] = None
ret['comment'] = (
'Sysctl value is currently set on the running system but '
'not in a config file. Sysctl option {0} set to be '
'changed to {1} in config file.'.format(name, value)
)
return ret
elif name in configured and name not in current:
ret['result'] = None
ret['comment'] = (
'Sysctl value {0} is present in configuration file but is not '
'present in the running config. The value {0} is set to be '
'changed to {1}'.format(name, value)
)
return ret
elif name in configured and name in current:
if six.text_type(value).split() == __salt__['sysctl.get'](name).split():
ret['result'] = True
ret['comment'] = (
'Sysctl value {0} = {1} is already set'
.format(name, value)
)
return ret
# otherwise, we don't have it set anywhere and need to set it
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} would be changed to {1}'.format(name, value)
)
return ret
try:
update = __salt__['sysctl.persist'](name, value, config)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = (
'Failed to set {0} to {1}: {2}'.format(name, value, exc)
)
return ret
if update == 'Updated':
ret['changes'] = {name: value}
ret['comment'] = 'Updated sysctl value {0} = {1}'.format(name, value)
elif update == 'Already set':
ret['comment'] = (
'Sysctl value {0} = {1} is already set'
.format(name, value)
)
return ret | python | def present(name, value, config=None):
'''
Ensure that the named sysctl value is set in memory and persisted to the
named configuration file. The default sysctl configuration file is
/etc/sysctl.conf
name
The name of the sysctl value to edit
value
The sysctl value to apply
config
The location of the sysctl configuration file. If not specified, the
proper location will be detected based on platform.
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
if config is None:
# Certain linux systems will ignore /etc/sysctl.conf, get the right
# default configuration file.
if 'sysctl.default_config' in __salt__:
config = __salt__['sysctl.default_config']()
else:
config = '/etc/sysctl.conf'
if __opts__['test']:
current = __salt__['sysctl.show']()
configured = __salt__['sysctl.show'](config_file=config)
if configured is None:
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} might be changed, we failed to check '
'config file at {1}. The file is either unreadable, or '
'missing.'.format(name, config)
)
return ret
if name in current and name not in configured:
if re.sub(' +|\t+', ' ', current[name]) != \
re.sub(' +|\t+', ' ', six.text_type(value)):
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} set to be changed to {1}'
.format(name, value)
)
return ret
else:
ret['result'] = None
ret['comment'] = (
'Sysctl value is currently set on the running system but '
'not in a config file. Sysctl option {0} set to be '
'changed to {1} in config file.'.format(name, value)
)
return ret
elif name in configured and name not in current:
ret['result'] = None
ret['comment'] = (
'Sysctl value {0} is present in configuration file but is not '
'present in the running config. The value {0} is set to be '
'changed to {1}'.format(name, value)
)
return ret
elif name in configured and name in current:
if six.text_type(value).split() == __salt__['sysctl.get'](name).split():
ret['result'] = True
ret['comment'] = (
'Sysctl value {0} = {1} is already set'
.format(name, value)
)
return ret
# otherwise, we don't have it set anywhere and need to set it
ret['result'] = None
ret['comment'] = (
'Sysctl option {0} would be changed to {1}'.format(name, value)
)
return ret
try:
update = __salt__['sysctl.persist'](name, value, config)
except CommandExecutionError as exc:
ret['result'] = False
ret['comment'] = (
'Failed to set {0} to {1}: {2}'.format(name, value, exc)
)
return ret
if update == 'Updated':
ret['changes'] = {name: value}
ret['comment'] = 'Updated sysctl value {0} = {1}'.format(name, value)
elif update == 'Already set':
ret['comment'] = (
'Sysctl value {0} = {1} is already set'
.format(name, value)
)
return ret | [
"def",
"present",
"(",
"name",
",",
"value",
",",
"config",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"if",
"config",
"is",
"Non... | Ensure that the named sysctl value is set in memory and persisted to the
named configuration file. The default sysctl configuration file is
/etc/sysctl.conf
name
The name of the sysctl value to edit
value
The sysctl value to apply
config
The location of the sysctl configuration file. If not specified, the
proper location will be detected based on platform. | [
"Ensure",
"that",
"the",
"named",
"sysctl",
"value",
"is",
"set",
"in",
"memory",
"and",
"persisted",
"to",
"the",
"named",
"configuration",
"file",
".",
"The",
"default",
"sysctl",
"configuration",
"file",
"is",
"/",
"etc",
"/",
"sysctl",
".",
"conf"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/sysctl.py#L33-L131 | train |
saltstack/salt | salt/grains/opts.py | opts | def opts():
'''
Return the minion configuration settings
'''
if __opts__.get('grain_opts', False) or \
(isinstance(__pillar__, dict) and __pillar__.get('grain_opts', False)):
return __opts__
return {} | python | def opts():
'''
Return the minion configuration settings
'''
if __opts__.get('grain_opts', False) or \
(isinstance(__pillar__, dict) and __pillar__.get('grain_opts', False)):
return __opts__
return {} | [
"def",
"opts",
"(",
")",
":",
"if",
"__opts__",
".",
"get",
"(",
"'grain_opts'",
",",
"False",
")",
"or",
"(",
"isinstance",
"(",
"__pillar__",
",",
"dict",
")",
"and",
"__pillar__",
".",
"get",
"(",
"'grain_opts'",
",",
"False",
")",
")",
":",
"retu... | Return the minion configuration settings | [
"Return",
"the",
"minion",
"configuration",
"settings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/opts.py#L9-L16 | train |
saltstack/salt | salt/modules/freebsd_update.py | _cmd | def _cmd(**kwargs):
'''
.. versionadded:: 2016.3.4
Private function that returns the freebsd-update command string to be
executed. It checks if any arguments are given to freebsd-update and appends
them accordingly.
'''
update_cmd = salt.utils.path.which('freebsd-update')
if not update_cmd:
raise CommandNotFoundError('"freebsd-update" command not found')
params = []
if 'basedir' in kwargs:
params.append('-b {0}'.format(kwargs['basedir']))
if 'workdir' in kwargs:
params.append('-d {0}'.format(kwargs['workdir']))
if 'conffile' in kwargs:
params.append('-f {0}'.format(kwargs['conffile']))
if 'force' in kwargs:
params.append('-F')
if 'key' in kwargs:
params.append('-k {0}'.format(kwargs['key']))
if 'newrelease' in kwargs:
params.append('-r {0}'.format(kwargs['newrelease']))
if 'server' in kwargs:
params.append('-s {0}'.format(kwargs['server']))
if 'address' in kwargs:
params.append('-t {0}'.format(kwargs['address']))
if params:
return '{0} {1}'.format(update_cmd, ' '.join(params))
return update_cmd | python | def _cmd(**kwargs):
'''
.. versionadded:: 2016.3.4
Private function that returns the freebsd-update command string to be
executed. It checks if any arguments are given to freebsd-update and appends
them accordingly.
'''
update_cmd = salt.utils.path.which('freebsd-update')
if not update_cmd:
raise CommandNotFoundError('"freebsd-update" command not found')
params = []
if 'basedir' in kwargs:
params.append('-b {0}'.format(kwargs['basedir']))
if 'workdir' in kwargs:
params.append('-d {0}'.format(kwargs['workdir']))
if 'conffile' in kwargs:
params.append('-f {0}'.format(kwargs['conffile']))
if 'force' in kwargs:
params.append('-F')
if 'key' in kwargs:
params.append('-k {0}'.format(kwargs['key']))
if 'newrelease' in kwargs:
params.append('-r {0}'.format(kwargs['newrelease']))
if 'server' in kwargs:
params.append('-s {0}'.format(kwargs['server']))
if 'address' in kwargs:
params.append('-t {0}'.format(kwargs['address']))
if params:
return '{0} {1}'.format(update_cmd, ' '.join(params))
return update_cmd | [
"def",
"_cmd",
"(",
"*",
"*",
"kwargs",
")",
":",
"update_cmd",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'freebsd-update'",
")",
"if",
"not",
"update_cmd",
":",
"raise",
"CommandNotFoundError",
"(",
"'\"freebsd-update\" command not found'",
... | .. versionadded:: 2016.3.4
Private function that returns the freebsd-update command string to be
executed. It checks if any arguments are given to freebsd-update and appends
them accordingly. | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"4"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L45-L77 | train |
saltstack/salt | salt/modules/freebsd_update.py | _wrapper | def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs):
'''
Helper function that wraps the execution of freebsd-update command.
orig:
Originating function that called _wrapper().
pre:
String that will be prepended to freebsd-update command.
post:
String that will be appended to freebsd-update command.
err_:
Dictionary on which return codes and stout/stderr are copied.
run_args:
Arguments to be passed on cmd.run_all.
kwargs:
Parameters of freebsd-update command.
'''
ret = '' # the message to be returned
cmd = _cmd(**kwargs)
cmd_str = ' '.join([x for x in (pre, cmd, post, orig)])
if run_args and isinstance(run_args, dict):
res = __salt__['cmd.run_all'](cmd_str, **run_args)
else:
res = __salt__['cmd.run_all'](cmd_str)
if isinstance(err_, dict): # copy return values if asked to
for k, v in six.itermitems(res):
err_[k] = v
if 'retcode' in res and res['retcode'] != 0:
msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x])
ret = 'Unable to run "{0}" with run_args="{1}". Error: {2}'.format(cmd_str, run_args, msg)
log.error(ret)
else:
try:
ret = res['stdout']
except KeyError:
log.error("cmd.run_all did not return a dictionary with a key named 'stdout'")
return ret | python | def _wrapper(orig, pre='', post='', err_=None, run_args=None, **kwargs):
'''
Helper function that wraps the execution of freebsd-update command.
orig:
Originating function that called _wrapper().
pre:
String that will be prepended to freebsd-update command.
post:
String that will be appended to freebsd-update command.
err_:
Dictionary on which return codes and stout/stderr are copied.
run_args:
Arguments to be passed on cmd.run_all.
kwargs:
Parameters of freebsd-update command.
'''
ret = '' # the message to be returned
cmd = _cmd(**kwargs)
cmd_str = ' '.join([x for x in (pre, cmd, post, orig)])
if run_args and isinstance(run_args, dict):
res = __salt__['cmd.run_all'](cmd_str, **run_args)
else:
res = __salt__['cmd.run_all'](cmd_str)
if isinstance(err_, dict): # copy return values if asked to
for k, v in six.itermitems(res):
err_[k] = v
if 'retcode' in res and res['retcode'] != 0:
msg = ' '.join([x for x in (res['stdout'], res['stderr']) if x])
ret = 'Unable to run "{0}" with run_args="{1}". Error: {2}'.format(cmd_str, run_args, msg)
log.error(ret)
else:
try:
ret = res['stdout']
except KeyError:
log.error("cmd.run_all did not return a dictionary with a key named 'stdout'")
return ret | [
"def",
"_wrapper",
"(",
"orig",
",",
"pre",
"=",
"''",
",",
"post",
"=",
"''",
",",
"err_",
"=",
"None",
",",
"run_args",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"''",
"# the message to be returned",
"cmd",
"=",
"_cmd",
"(",
"*"... | Helper function that wraps the execution of freebsd-update command.
orig:
Originating function that called _wrapper().
pre:
String that will be prepended to freebsd-update command.
post:
String that will be appended to freebsd-update command.
err_:
Dictionary on which return codes and stout/stderr are copied.
run_args:
Arguments to be passed on cmd.run_all.
kwargs:
Parameters of freebsd-update command. | [
"Helper",
"function",
"that",
"wraps",
"the",
"execution",
"of",
"freebsd",
"-",
"update",
"command",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L80-L123 | train |
saltstack/salt | salt/modules/freebsd_update.py | fetch | def fetch(**kwargs):
'''
.. versionadded:: 2016.3.4
freebsd-update fetch wrapper. Based on the currently installed world and the
configuration options set, fetch all available binary updates.
kwargs:
Parameters of freebsd-update command.
'''
# fetch continues when no controlling terminal is present
pre = ''
post = ''
run_args = {}
if float(__grains__['osrelease']) >= 10.2:
post += '--not-running-from-cron'
else:
pre += ' env PAGER=cat'
run_args['python_shell'] = True
return _wrapper('fetch', pre=pre, post=post, run_args=run_args, **kwargs) | python | def fetch(**kwargs):
'''
.. versionadded:: 2016.3.4
freebsd-update fetch wrapper. Based on the currently installed world and the
configuration options set, fetch all available binary updates.
kwargs:
Parameters of freebsd-update command.
'''
# fetch continues when no controlling terminal is present
pre = ''
post = ''
run_args = {}
if float(__grains__['osrelease']) >= 10.2:
post += '--not-running-from-cron'
else:
pre += ' env PAGER=cat'
run_args['python_shell'] = True
return _wrapper('fetch', pre=pre, post=post, run_args=run_args, **kwargs) | [
"def",
"fetch",
"(",
"*",
"*",
"kwargs",
")",
":",
"# fetch continues when no controlling terminal is present",
"pre",
"=",
"''",
"post",
"=",
"''",
"run_args",
"=",
"{",
"}",
"if",
"float",
"(",
"__grains__",
"[",
"'osrelease'",
"]",
")",
">=",
"10.2",
":",... | .. versionadded:: 2016.3.4
freebsd-update fetch wrapper. Based on the currently installed world and the
configuration options set, fetch all available binary updates.
kwargs:
Parameters of freebsd-update command. | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"4"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L126-L145 | train |
saltstack/salt | salt/modules/freebsd_update.py | update | def update(**kwargs):
'''
.. versionadded:: 2016.3.4
Command that simplifies freebsd-update by running freebsd-update fetch first
and then freebsd-update install.
kwargs:
Parameters of freebsd-update command.
'''
stdout = {}
for mode in ('fetch', 'install'):
err_ = {}
ret = _wrapper(mode, err_=err_, **kwargs)
if 'retcode' in err_ and err_['retcode'] != 0:
return ret
if 'stdout' in err_:
stdout[mode] = err_['stdout']
return '\n'.join(['{0}: {1}'.format(k, v) for (k, v) in six.iteritems(stdout)]) | python | def update(**kwargs):
'''
.. versionadded:: 2016.3.4
Command that simplifies freebsd-update by running freebsd-update fetch first
and then freebsd-update install.
kwargs:
Parameters of freebsd-update command.
'''
stdout = {}
for mode in ('fetch', 'install'):
err_ = {}
ret = _wrapper(mode, err_=err_, **kwargs)
if 'retcode' in err_ and err_['retcode'] != 0:
return ret
if 'stdout' in err_:
stdout[mode] = err_['stdout']
return '\n'.join(['{0}: {1}'.format(k, v) for (k, v) in six.iteritems(stdout)]) | [
"def",
"update",
"(",
"*",
"*",
"kwargs",
")",
":",
"stdout",
"=",
"{",
"}",
"for",
"mode",
"in",
"(",
"'fetch'",
",",
"'install'",
")",
":",
"err_",
"=",
"{",
"}",
"ret",
"=",
"_wrapper",
"(",
"mode",
",",
"err_",
"=",
"err_",
",",
"*",
"*",
... | .. versionadded:: 2016.3.4
Command that simplifies freebsd-update by running freebsd-update fetch first
and then freebsd-update install.
kwargs:
Parameters of freebsd-update command. | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"4"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/freebsd_update.py#L174-L193 | train |
saltstack/salt | salt/states/flatpak.py | uninstalled | def uninstalled(name):
'''
Ensure that the named package is not installed.
Args:
name (str): The flatpak package.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
uninstall_package:
flatpack.uninstalled:
- name: gimp
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_installed'](name)
if not old:
ret['comment'] = 'Package {0} is not installed'.format(name)
ret['result'] = True
return ret
else:
if __opts__['test']:
ret['comment'] = 'Package {0} would have been uninstalled'.format(name)
ret['changes']['old'] = old[0]['version']
ret['changes']['new'] = None
ret['result'] = None
return ret
__salt__['flatpak.uninstall'](name)
if not __salt__['flatpak.is_installed'](name):
ret['comment'] = 'Package {0} uninstalled'.format(name)
ret['changes']['old'] = old[0]['version']
ret['changes']['new'] = None
ret['result'] = True
return ret | python | def uninstalled(name):
'''
Ensure that the named package is not installed.
Args:
name (str): The flatpak package.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
uninstall_package:
flatpack.uninstalled:
- name: gimp
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_installed'](name)
if not old:
ret['comment'] = 'Package {0} is not installed'.format(name)
ret['result'] = True
return ret
else:
if __opts__['test']:
ret['comment'] = 'Package {0} would have been uninstalled'.format(name)
ret['changes']['old'] = old[0]['version']
ret['changes']['new'] = None
ret['result'] = None
return ret
__salt__['flatpak.uninstall'](name)
if not __salt__['flatpak.is_installed'](name):
ret['comment'] = 'Package {0} uninstalled'.format(name)
ret['changes']['old'] = old[0]['version']
ret['changes']['new'] = None
ret['result'] = True
return ret | [
"def",
"uninstalled",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"old",
"=",
"__salt__",
"[",
"'flatpak.is_installed'",
"]",
"(",
"na... | Ensure that the named package is not installed.
Args:
name (str): The flatpak package.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
uninstall_package:
flatpack.uninstalled:
- name: gimp | [
"Ensure",
"that",
"the",
"named",
"package",
"is",
"not",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/flatpak.py#L79-L121 | train |
saltstack/salt | salt/states/flatpak.py | add_remote | def add_remote(name, location):
'''
Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
add_flathub:
flatpack.add_remote:
- name: flathub
- location: https://flathub.org/repo/flathub.flatpakrepo
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_remote_added'](name)
if not old:
if __opts__['test']:
ret['comment'] = 'Remote "{0}" would have been added'.format(name)
ret['changes']['new'] = name
ret['changes']['old'] = None
ret['result'] = None
return ret
install_ret = __salt__['flatpak.add_remote'](name)
if __salt__['flatpak.is_remote_added'](name):
ret['comment'] = 'Remote "{0}" was added'.format(name)
ret['changes']['new'] = name
ret['changes']['old'] = None
ret['result'] = True
return ret
ret['comment'] = 'Failed to add remote "{0}"'.format(name)
ret['comment'] += '\noutput:\n' + install_ret['output']
ret['result'] = False
return ret
ret['comment'] = 'Remote "{0}" already exists'.format(name)
if __opts__['test']:
ret['result'] = None
return ret
ret['result'] = True
return ret | python | def add_remote(name, location):
'''
Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
add_flathub:
flatpack.add_remote:
- name: flathub
- location: https://flathub.org/repo/flathub.flatpakrepo
'''
ret = {'name': name,
'changes': {},
'result': None,
'comment': ''}
old = __salt__['flatpak.is_remote_added'](name)
if not old:
if __opts__['test']:
ret['comment'] = 'Remote "{0}" would have been added'.format(name)
ret['changes']['new'] = name
ret['changes']['old'] = None
ret['result'] = None
return ret
install_ret = __salt__['flatpak.add_remote'](name)
if __salt__['flatpak.is_remote_added'](name):
ret['comment'] = 'Remote "{0}" was added'.format(name)
ret['changes']['new'] = name
ret['changes']['old'] = None
ret['result'] = True
return ret
ret['comment'] = 'Failed to add remote "{0}"'.format(name)
ret['comment'] += '\noutput:\n' + install_ret['output']
ret['result'] = False
return ret
ret['comment'] = 'Remote "{0}" already exists'.format(name)
if __opts__['test']:
ret['result'] = None
return ret
ret['result'] = True
return ret | [
"def",
"add_remote",
"(",
"name",
",",
"location",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"old",
"=",
"__salt__",
"[",
"'flatpak.is_remote_added... | Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
Example:
.. code-block:: yaml
add_flathub:
flatpack.add_remote:
- name: flathub
- location: https://flathub.org/repo/flathub.flatpakrepo | [
"Adds",
"a",
"new",
"location",
"to",
"install",
"flatpak",
"packages",
"from",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/flatpak.py#L124-L177 | train |
saltstack/salt | salt/modules/smartos_nictagadm.py | list_nictags | def list_nictags(include_etherstubs=True):
'''
List all nictags
include_etherstubs : boolean
toggle include of etherstubs
CLI Example:
.. code-block:: bash
salt '*' nictagadm.list
'''
ret = {}
cmd = 'nictagadm list -d "|" -p{0}'.format(
' -L' if not include_etherstubs else ''
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
if retcode != 0:
ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.'
else:
header = ['name', 'macaddress', 'link', 'type']
for nictag in res['stdout'].splitlines():
nictag = nictag.split('|')
nictag_data = {}
for field in header:
nictag_data[field] = nictag[header.index(field)]
ret[nictag_data['name']] = nictag_data
del ret[nictag_data['name']]['name']
return ret | python | def list_nictags(include_etherstubs=True):
'''
List all nictags
include_etherstubs : boolean
toggle include of etherstubs
CLI Example:
.. code-block:: bash
salt '*' nictagadm.list
'''
ret = {}
cmd = 'nictagadm list -d "|" -p{0}'.format(
' -L' if not include_etherstubs else ''
)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
if retcode != 0:
ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of nictags.'
else:
header = ['name', 'macaddress', 'link', 'type']
for nictag in res['stdout'].splitlines():
nictag = nictag.split('|')
nictag_data = {}
for field in header:
nictag_data[field] = nictag[header.index(field)]
ret[nictag_data['name']] = nictag_data
del ret[nictag_data['name']]['name']
return ret | [
"def",
"list_nictags",
"(",
"include_etherstubs",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'nictagadm list -d \"|\" -p{0}'",
".",
"format",
"(",
"' -L'",
"if",
"not",
"include_etherstubs",
"else",
"''",
")",
"res",
"=",
"__salt__",
"[",
"'cm... | List all nictags
include_etherstubs : boolean
toggle include of etherstubs
CLI Example:
.. code-block:: bash
salt '*' nictagadm.list | [
"List",
"all",
"nictags"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L48-L78 | train |
saltstack/salt | salt/modules/smartos_nictagadm.py | vms | def vms(nictag):
'''
List all vms connect to nictag
nictag : string
name of nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.vms admin
'''
ret = {}
cmd = 'nictagadm vms {0}'.format(nictag)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
if retcode != 0:
ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.'
else:
ret = res['stdout'].splitlines()
return ret | python | def vms(nictag):
'''
List all vms connect to nictag
nictag : string
name of nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.vms admin
'''
ret = {}
cmd = 'nictagadm vms {0}'.format(nictag)
res = __salt__['cmd.run_all'](cmd)
retcode = res['retcode']
if retcode != 0:
ret['Error'] = res['stderr'] if 'stderr' in res else 'Failed to get list of vms.'
else:
ret = res['stdout'].splitlines()
return ret | [
"def",
"vms",
"(",
"nictag",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'nictagadm vms {0}'",
".",
"format",
"(",
"nictag",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"retcode",
"=",
"res",
"[",
"'retcode'",
"]",
"if",... | List all vms connect to nictag
nictag : string
name of nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.vms admin | [
"List",
"all",
"vms",
"connect",
"to",
"nictag"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L81-L102 | train |
saltstack/salt | salt/modules/smartos_nictagadm.py | exists | def exists(*nictag, **kwargs):
'''
Check if nictags exists
nictag : string
one or more nictags to check
verbose : boolean
return list of nictags
CLI Example:
.. code-block:: bash
salt '*' nictagadm.exists admin
'''
ret = {}
if not nictag:
return {'Error': 'Please provide at least one nictag to check.'}
cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag))
res = __salt__['cmd.run_all'](cmd)
if not kwargs.get('verbose', False):
ret = res['retcode'] == 0
else:
missing = res['stderr'].splitlines()
for nt in nictag:
ret[nt] = nt not in missing
return ret | python | def exists(*nictag, **kwargs):
'''
Check if nictags exists
nictag : string
one or more nictags to check
verbose : boolean
return list of nictags
CLI Example:
.. code-block:: bash
salt '*' nictagadm.exists admin
'''
ret = {}
if not nictag:
return {'Error': 'Please provide at least one nictag to check.'}
cmd = 'nictagadm exists -l {0}'.format(' '.join(nictag))
res = __salt__['cmd.run_all'](cmd)
if not kwargs.get('verbose', False):
ret = res['retcode'] == 0
else:
missing = res['stderr'].splitlines()
for nt in nictag:
ret[nt] = nt not in missing
return ret | [
"def",
"exists",
"(",
"*",
"nictag",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"nictag",
":",
"return",
"{",
"'Error'",
":",
"'Please provide at least one nictag to check.'",
"}",
"cmd",
"=",
"'nictagadm exists -l {0}'",
".",
"for... | Check if nictags exists
nictag : string
one or more nictags to check
verbose : boolean
return list of nictags
CLI Example:
.. code-block:: bash
salt '*' nictagadm.exists admin | [
"Check",
"if",
"nictags",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L105-L134 | train |
saltstack/salt | salt/modules/smartos_nictagadm.py | add | def add(name, mac, mtu=1500):
'''
Add a new nictag
name : string
name of new nictag
mac : string
mac of parent interface or 'etherstub' to create a ether stub
mtu : int
MTU (ignored for etherstubs)
CLI Example:
.. code-block:: bash
salt '*' nictagadm.add storage0 etherstub
salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000
'''
ret = {}
if mtu > 9000 or mtu < 1500:
return {'Error': 'mtu must be a value between 1500 and 9000.'}
if mac != 'etherstub':
cmd = 'dladm show-phys -m -p -o address'
res = __salt__['cmd.run_all'](cmd)
# dladm prints '00' as '0', so account for that.
if mac.replace('00', '0') not in res['stdout'].splitlines():
return {'Error': '{0} is not present on this system.'.format(mac)}
if mac == 'etherstub':
cmd = 'nictagadm add -l {0}'.format(name)
res = __salt__['cmd.run_all'](cmd)
else:
cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name)
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
return True
else:
return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} | python | def add(name, mac, mtu=1500):
'''
Add a new nictag
name : string
name of new nictag
mac : string
mac of parent interface or 'etherstub' to create a ether stub
mtu : int
MTU (ignored for etherstubs)
CLI Example:
.. code-block:: bash
salt '*' nictagadm.add storage0 etherstub
salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000
'''
ret = {}
if mtu > 9000 or mtu < 1500:
return {'Error': 'mtu must be a value between 1500 and 9000.'}
if mac != 'etherstub':
cmd = 'dladm show-phys -m -p -o address'
res = __salt__['cmd.run_all'](cmd)
# dladm prints '00' as '0', so account for that.
if mac.replace('00', '0') not in res['stdout'].splitlines():
return {'Error': '{0} is not present on this system.'.format(mac)}
if mac == 'etherstub':
cmd = 'nictagadm add -l {0}'.format(name)
res = __salt__['cmd.run_all'](cmd)
else:
cmd = 'nictagadm add -p mtu={0},mac={1} {2}'.format(mtu, mac, name)
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
return True
else:
return {'Error': 'failed to create nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} | [
"def",
"add",
"(",
"name",
",",
"mac",
",",
"mtu",
"=",
"1500",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"mtu",
">",
"9000",
"or",
"mtu",
"<",
"1500",
":",
"return",
"{",
"'Error'",
":",
"'mtu must be a value between 1500 and 9000.'",
"}",
"if",
"mac",
... | Add a new nictag
name : string
name of new nictag
mac : string
mac of parent interface or 'etherstub' to create a ether stub
mtu : int
MTU (ignored for etherstubs)
CLI Example:
.. code-block:: bash
salt '*' nictagadm.add storage0 etherstub
salt '*' nictagadm.add trunk0 'DE:AD:OO:OO:BE:EF' 9000 | [
"Add",
"a",
"new",
"nictag"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L137-L176 | train |
saltstack/salt | salt/modules/smartos_nictagadm.py | update | def update(name, mac=None, mtu=None):
'''
Update a nictag
name : string
name of nictag
mac : string
optional new mac for nictag
mtu : int
optional new MTU for nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.update trunk mtu=9000
'''
ret = {}
if name not in list_nictags():
return {'Error': 'nictag {0} does not exists.'.format(name)}
if not mtu and not mac:
return {'Error': 'please provide either mac or/and mtu.'}
if mtu:
if mtu > 9000 or mtu < 1500:
return {'Error': 'mtu must be a value between 1500 and 9000.'}
if mac:
if mac == 'etherstub':
return {'Error': 'cannot update a nic with "etherstub".'}
else:
cmd = 'dladm show-phys -m -p -o address'
res = __salt__['cmd.run_all'](cmd)
# dladm prints '00' as '0', so account for that.
if mac.replace('00', '0') not in res['stdout'].splitlines():
return {'Error': '{0} is not present on this system.'.format(mac)}
if mac and mtu:
properties = "mtu={0},mac={1}".format(mtu, mac)
elif mac:
properties = "mac={0}".format(mac) if mac else ""
elif mtu:
properties = "mtu={0}".format(mtu) if mtu else ""
cmd = 'nictagadm update -p {0} {1}'.format(properties, name)
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
return True
else:
return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} | python | def update(name, mac=None, mtu=None):
'''
Update a nictag
name : string
name of nictag
mac : string
optional new mac for nictag
mtu : int
optional new MTU for nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.update trunk mtu=9000
'''
ret = {}
if name not in list_nictags():
return {'Error': 'nictag {0} does not exists.'.format(name)}
if not mtu and not mac:
return {'Error': 'please provide either mac or/and mtu.'}
if mtu:
if mtu > 9000 or mtu < 1500:
return {'Error': 'mtu must be a value between 1500 and 9000.'}
if mac:
if mac == 'etherstub':
return {'Error': 'cannot update a nic with "etherstub".'}
else:
cmd = 'dladm show-phys -m -p -o address'
res = __salt__['cmd.run_all'](cmd)
# dladm prints '00' as '0', so account for that.
if mac.replace('00', '0') not in res['stdout'].splitlines():
return {'Error': '{0} is not present on this system.'.format(mac)}
if mac and mtu:
properties = "mtu={0},mac={1}".format(mtu, mac)
elif mac:
properties = "mac={0}".format(mac) if mac else ""
elif mtu:
properties = "mtu={0}".format(mtu) if mtu else ""
cmd = 'nictagadm update -p {0} {1}'.format(properties, name)
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
return True
else:
return {'Error': 'failed to update nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} | [
"def",
"update",
"(",
"name",
",",
"mac",
"=",
"None",
",",
"mtu",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"name",
"not",
"in",
"list_nictags",
"(",
")",
":",
"return",
"{",
"'Error'",
":",
"'nictag {0} does not exists.'",
".",
"format",
"... | Update a nictag
name : string
name of nictag
mac : string
optional new mac for nictag
mtu : int
optional new MTU for nictag
CLI Example:
.. code-block:: bash
salt '*' nictagadm.update trunk mtu=9000 | [
"Update",
"a",
"nictag"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L179-L228 | train |
saltstack/salt | salt/modules/smartos_nictagadm.py | delete | def delete(name, force=False):
'''
Delete nictag
name : string
nictag to delete
force : boolean
force delete even if vms attached
CLI Example:
.. code-block:: bash
salt '*' nictagadm.exists admin
'''
ret = {}
if name not in list_nictags():
return True
cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name)
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
return True
else:
return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} | python | def delete(name, force=False):
'''
Delete nictag
name : string
nictag to delete
force : boolean
force delete even if vms attached
CLI Example:
.. code-block:: bash
salt '*' nictagadm.exists admin
'''
ret = {}
if name not in list_nictags():
return True
cmd = 'nictagadm delete {0}{1}'.format("-f " if force else "", name)
res = __salt__['cmd.run_all'](cmd)
if res['retcode'] == 0:
return True
else:
return {'Error': 'failed to delete nictag.' if 'stderr' not in res and res['stderr'] == '' else res['stderr']} | [
"def",
"delete",
"(",
"name",
",",
"force",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"name",
"not",
"in",
"list_nictags",
"(",
")",
":",
"return",
"True",
"cmd",
"=",
"'nictagadm delete {0}{1}'",
".",
"format",
"(",
"\"-f \"",
"if",
"force",... | Delete nictag
name : string
nictag to delete
force : boolean
force delete even if vms attached
CLI Example:
.. code-block:: bash
salt '*' nictagadm.exists admin | [
"Delete",
"nictag"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smartos_nictagadm.py#L231-L257 | train |
saltstack/salt | salt/proxy/philips_hue.py | init | def init(cnf):
'''
Initialize the module.
'''
CONFIG['host'] = cnf.get('proxy', {}).get('host')
if not CONFIG['host']:
raise MinionError(message="Cannot find 'host' parameter in the proxy configuration")
CONFIG['user'] = cnf.get('proxy', {}).get('user')
if not CONFIG['user']:
raise MinionError(message="Cannot find 'user' parameter in the proxy configuration")
CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) | python | def init(cnf):
'''
Initialize the module.
'''
CONFIG['host'] = cnf.get('proxy', {}).get('host')
if not CONFIG['host']:
raise MinionError(message="Cannot find 'host' parameter in the proxy configuration")
CONFIG['user'] = cnf.get('proxy', {}).get('user')
if not CONFIG['user']:
raise MinionError(message="Cannot find 'user' parameter in the proxy configuration")
CONFIG['uri'] = "/api/{0}".format(CONFIG['user']) | [
"def",
"init",
"(",
"cnf",
")",
":",
"CONFIG",
"[",
"'host'",
"]",
"=",
"cnf",
".",
"get",
"(",
"'proxy'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'host'",
")",
"if",
"not",
"CONFIG",
"[",
"'host'",
"]",
":",
"raise",
"MinionError",
"(",
"message",... | Initialize the module. | [
"Initialize",
"the",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L79-L91 | train |
saltstack/salt | salt/proxy/philips_hue.py | _query | def _query(lamp_id, state, action='', method='GET'):
'''
Query the URI
:return:
'''
# Because salt.utils.query is that dreadful... :(
err = None
url = "{0}/lights{1}".format(CONFIG['uri'],
lamp_id and '/{0}'.format(lamp_id) or '') \
+ (action and "/{0}".format(action) or '')
conn = http_client.HTTPConnection(CONFIG['host'])
if method == 'PUT':
conn.request(method, url, salt.utils.json.dumps(state))
else:
conn.request(method, url)
resp = conn.getresponse()
if resp.status == http_client.OK:
res = salt.utils.json.loads(resp.read())
else:
err = "HTTP error: {0}, {1}".format(resp.status, resp.reason)
conn.close()
if err:
raise CommandExecutionError(err)
return res | python | def _query(lamp_id, state, action='', method='GET'):
'''
Query the URI
:return:
'''
# Because salt.utils.query is that dreadful... :(
err = None
url = "{0}/lights{1}".format(CONFIG['uri'],
lamp_id and '/{0}'.format(lamp_id) or '') \
+ (action and "/{0}".format(action) or '')
conn = http_client.HTTPConnection(CONFIG['host'])
if method == 'PUT':
conn.request(method, url, salt.utils.json.dumps(state))
else:
conn.request(method, url)
resp = conn.getresponse()
if resp.status == http_client.OK:
res = salt.utils.json.loads(resp.read())
else:
err = "HTTP error: {0}, {1}".format(resp.status, resp.reason)
conn.close()
if err:
raise CommandExecutionError(err)
return res | [
"def",
"_query",
"(",
"lamp_id",
",",
"state",
",",
"action",
"=",
"''",
",",
"method",
"=",
"'GET'",
")",
":",
"# Because salt.utils.query is that dreadful... :(",
"err",
"=",
"None",
"url",
"=",
"\"{0}/lights{1}\"",
".",
"format",
"(",
"CONFIG",
"[",
"'uri'"... | Query the URI
:return: | [
"Query",
"the",
"URI"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L110-L137 | train |
saltstack/salt | salt/proxy/philips_hue.py | _set | def _set(lamp_id, state, method="state"):
'''
Set state to the device by ID.
:param lamp_id:
:param state:
:return:
'''
try:
res = _query(lamp_id, state, action=method, method='PUT')
except Exception as err:
raise CommandExecutionError(err)
res = len(res) > 1 and res[-1] or res[0]
if res.get('success'):
res = {'result': True}
elif res.get('error'):
res = {'result': False,
'description': res['error']['description'],
'type': res['error']['type']}
return res | python | def _set(lamp_id, state, method="state"):
'''
Set state to the device by ID.
:param lamp_id:
:param state:
:return:
'''
try:
res = _query(lamp_id, state, action=method, method='PUT')
except Exception as err:
raise CommandExecutionError(err)
res = len(res) > 1 and res[-1] or res[0]
if res.get('success'):
res = {'result': True}
elif res.get('error'):
res = {'result': False,
'description': res['error']['description'],
'type': res['error']['type']}
return res | [
"def",
"_set",
"(",
"lamp_id",
",",
"state",
",",
"method",
"=",
"\"state\"",
")",
":",
"try",
":",
"res",
"=",
"_query",
"(",
"lamp_id",
",",
"state",
",",
"action",
"=",
"method",
",",
"method",
"=",
"'PUT'",
")",
"except",
"Exception",
"as",
"err"... | Set state to the device by ID.
:param lamp_id:
:param state:
:return: | [
"Set",
"state",
"to",
"the",
"device",
"by",
"ID",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L140-L161 | train |
saltstack/salt | salt/proxy/philips_hue.py | _get_devices | def _get_devices(params):
'''
Parse device(s) ID(s) from the common params.
:param params:
:return:
'''
if 'id' not in params:
raise CommandExecutionError("Parameter ID is required.")
return type(params['id']) == int and [params['id']] \
or [int(dev) for dev in params['id'].split(",")] | python | def _get_devices(params):
'''
Parse device(s) ID(s) from the common params.
:param params:
:return:
'''
if 'id' not in params:
raise CommandExecutionError("Parameter ID is required.")
return type(params['id']) == int and [params['id']] \
or [int(dev) for dev in params['id'].split(",")] | [
"def",
"_get_devices",
"(",
"params",
")",
":",
"if",
"'id'",
"not",
"in",
"params",
":",
"raise",
"CommandExecutionError",
"(",
"\"Parameter ID is required.\"",
")",
"return",
"type",
"(",
"params",
"[",
"'id'",
"]",
")",
"==",
"int",
"and",
"[",
"params",
... | Parse device(s) ID(s) from the common params.
:param params:
:return: | [
"Parse",
"device",
"(",
"s",
")",
"ID",
"(",
"s",
")",
"from",
"the",
"common",
"params",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L164-L175 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_lights | def call_lights(*args, **kwargs):
'''
Get info about all available lamps.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.lights
salt '*' hue.lights id=1
salt '*' hue.lights id=1,2,3
'''
res = dict()
lights = _get_lights()
for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()):
if lights.get(six.text_type(dev_id)):
res[dev_id] = lights[six.text_type(dev_id)]
return res or False | python | def call_lights(*args, **kwargs):
'''
Get info about all available lamps.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.lights
salt '*' hue.lights id=1
salt '*' hue.lights id=1,2,3
'''
res = dict()
lights = _get_lights()
for dev_id in 'id' in kwargs and _get_devices(kwargs) or sorted(lights.keys()):
if lights.get(six.text_type(dev_id)):
res[dev_id] = lights[six.text_type(dev_id)]
return res or False | [
"def",
"call_lights",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"dict",
"(",
")",
"lights",
"=",
"_get_lights",
"(",
")",
"for",
"dev_id",
"in",
"'id'",
"in",
"kwargs",
"and",
"_get_devices",
"(",
"kwargs",
")",
"or",
"sorted",... | Get info about all available lamps.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.lights
salt '*' hue.lights id=1
salt '*' hue.lights id=1,2,3 | [
"Get",
"info",
"about",
"all",
"available",
"lamps",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L186-L208 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_switch | def call_switch(*args, **kwargs):
'''
Switch lamp ON/OFF.
If no particular state is passed,
then lamp will be switched to the opposite state.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **on**: True or False. Inverted current, if omitted
CLI Example:
.. code-block:: bash
salt '*' hue.switch
salt '*' hue.switch id=1
salt '*' hue.switch id=1,2,3 on=True
'''
out = dict()
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
if 'on' in kwargs:
state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF
else:
# Invert the current state
state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON
out[dev_id] = _set(dev_id, state)
return out | python | def call_switch(*args, **kwargs):
'''
Switch lamp ON/OFF.
If no particular state is passed,
then lamp will be switched to the opposite state.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **on**: True or False. Inverted current, if omitted
CLI Example:
.. code-block:: bash
salt '*' hue.switch
salt '*' hue.switch id=1
salt '*' hue.switch id=1,2,3 on=True
'''
out = dict()
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
if 'on' in kwargs:
state = kwargs['on'] and Const.LAMP_ON or Const.LAMP_OFF
else:
# Invert the current state
state = devices[six.text_type(dev_id)]['state']['on'] and Const.LAMP_OFF or Const.LAMP_ON
out[dev_id] = _set(dev_id, state)
return out | [
"def",
"call_switch",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"dict",
"(",
")",
"devices",
"=",
"_get_lights",
"(",
")",
"for",
"dev_id",
"in",
"'id'",
"not",
"in",
"kwargs",
"and",
"sorted",
"(",
"devices",
".",
"keys",
"(... | Switch lamp ON/OFF.
If no particular state is passed,
then lamp will be switched to the opposite state.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **on**: True or False. Inverted current, if omitted
CLI Example:
.. code-block:: bash
salt '*' hue.switch
salt '*' hue.switch id=1
salt '*' hue.switch id=1,2,3 on=True | [
"Switch",
"lamp",
"ON",
"/",
"OFF",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L211-L241 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_blink | def call_blink(*args, **kwargs):
'''
Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec.
CLI Example:
.. code-block:: bash
salt '*' hue.blink id=1
salt '*' hue.blink id=1,2,3
'''
devices = _get_lights()
pause = kwargs.get('pause', 0)
res = dict()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
state = devices[six.text_type(dev_id)]['state']['on']
_set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON)
if pause:
time.sleep(pause)
res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON)
return res | python | def call_blink(*args, **kwargs):
'''
Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec.
CLI Example:
.. code-block:: bash
salt '*' hue.blink id=1
salt '*' hue.blink id=1,2,3
'''
devices = _get_lights()
pause = kwargs.get('pause', 0)
res = dict()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
state = devices[six.text_type(dev_id)]['state']['on']
_set(dev_id, state and Const.LAMP_OFF or Const.LAMP_ON)
if pause:
time.sleep(pause)
res[dev_id] = _set(dev_id, not state and Const.LAMP_OFF or Const.LAMP_ON)
return res | [
"def",
"call_blink",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"devices",
"=",
"_get_lights",
"(",
")",
"pause",
"=",
"kwargs",
".",
"get",
"(",
"'pause'",
",",
"0",
")",
"res",
"=",
"dict",
"(",
")",
"for",
"dev_id",
"in",
"'id'",
"no... | Blink a lamp. If lamp is ON, then blink ON-OFF-ON, otherwise OFF-ON-OFF.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **pause**: Time in seconds. Can be less than 1, i.e. 0.7, 0.5 sec.
CLI Example:
.. code-block:: bash
salt '*' hue.blink id=1
salt '*' hue.blink id=1,2,3 | [
"Blink",
"a",
"lamp",
".",
"If",
"lamp",
"is",
"ON",
"then",
"blink",
"ON",
"-",
"OFF",
"-",
"ON",
"otherwise",
"OFF",
"-",
"ON",
"-",
"OFF",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L244-L270 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_ping | def call_ping(*args, **kwargs):
'''
Ping the lamps by issuing a short inversion blink to all available devices.
CLI Example:
.. code-block:: bash
salt '*' hue.ping
'''
errors = dict()
for dev_id, dev_status in call_blink().items():
if not dev_status['result']:
errors[dev_id] = False
return errors or True | python | def call_ping(*args, **kwargs):
'''
Ping the lamps by issuing a short inversion blink to all available devices.
CLI Example:
.. code-block:: bash
salt '*' hue.ping
'''
errors = dict()
for dev_id, dev_status in call_blink().items():
if not dev_status['result']:
errors[dev_id] = False
return errors or True | [
"def",
"call_ping",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"errors",
"=",
"dict",
"(",
")",
"for",
"dev_id",
",",
"dev_status",
"in",
"call_blink",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"not",
"dev_status",
"[",
"'result'",
"]"... | Ping the lamps by issuing a short inversion blink to all available devices.
CLI Example:
.. code-block:: bash
salt '*' hue.ping | [
"Ping",
"the",
"lamps",
"by",
"issuing",
"a",
"short",
"inversion",
"blink",
"to",
"all",
"available",
"devices",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L273-L288 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_status | def call_status(*args, **kwargs):
'''
Return the status of the lamps.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.status
salt '*' hue.status id=1
salt '*' hue.status id=1,2,3
'''
res = dict()
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
dev_id = six.text_type(dev_id)
res[dev_id] = {
'on': devices[dev_id]['state']['on'],
'reachable': devices[dev_id]['state']['reachable']
}
return res | python | def call_status(*args, **kwargs):
'''
Return the status of the lamps.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.status
salt '*' hue.status id=1
salt '*' hue.status id=1,2,3
'''
res = dict()
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
dev_id = six.text_type(dev_id)
res[dev_id] = {
'on': devices[dev_id]['state']['on'],
'reachable': devices[dev_id]['state']['reachable']
}
return res | [
"def",
"call_status",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"dict",
"(",
")",
"devices",
"=",
"_get_lights",
"(",
")",
"for",
"dev_id",
"in",
"'id'",
"not",
"in",
"kwargs",
"and",
"sorted",
"(",
"devices",
".",
"keys",
"(... | Return the status of the lamps.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.status
salt '*' hue.status id=1
salt '*' hue.status id=1,2,3 | [
"Return",
"the",
"status",
"of",
"the",
"lamps",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L291-L316 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_rename | def call_rename(*args, **kwargs):
'''
Rename a device.
Options:
* **id**: Specifies a device ID. Only one device at a time.
* **title**: Title of the device.
CLI Example:
.. code-block:: bash
salt '*' hue.rename id=1 title='WC for cats'
'''
dev_id = _get_devices(kwargs)
if len(dev_id) > 1:
raise CommandExecutionError("Only one device can be renamed at a time")
if 'title' not in kwargs:
raise CommandExecutionError("Title is missing")
return _set(dev_id[0], {"name": kwargs['title']}, method="") | python | def call_rename(*args, **kwargs):
'''
Rename a device.
Options:
* **id**: Specifies a device ID. Only one device at a time.
* **title**: Title of the device.
CLI Example:
.. code-block:: bash
salt '*' hue.rename id=1 title='WC for cats'
'''
dev_id = _get_devices(kwargs)
if len(dev_id) > 1:
raise CommandExecutionError("Only one device can be renamed at a time")
if 'title' not in kwargs:
raise CommandExecutionError("Title is missing")
return _set(dev_id[0], {"name": kwargs['title']}, method="") | [
"def",
"call_rename",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"dev_id",
"=",
"_get_devices",
"(",
"kwargs",
")",
"if",
"len",
"(",
"dev_id",
")",
">",
"1",
":",
"raise",
"CommandExecutionError",
"(",
"\"Only one device can be renamed at a time\"",... | Rename a device.
Options:
* **id**: Specifies a device ID. Only one device at a time.
* **title**: Title of the device.
CLI Example:
.. code-block:: bash
salt '*' hue.rename id=1 title='WC for cats' | [
"Rename",
"a",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L319-L341 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_alert | def call_alert(*args, **kwargs):
'''
Lamp alert
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **on**: Turns on or off an alert. Default is True.
CLI Example:
.. code-block:: bash
salt '*' hue.alert
salt '*' hue.alert id=1
salt '*' hue.alert id=1,2,3 on=false
'''
res = dict()
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"})
return res | python | def call_alert(*args, **kwargs):
'''
Lamp alert
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **on**: Turns on or off an alert. Default is True.
CLI Example:
.. code-block:: bash
salt '*' hue.alert
salt '*' hue.alert id=1
salt '*' hue.alert id=1,2,3 on=false
'''
res = dict()
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"alert": kwargs.get("on", True) and "lselect" or "none"})
return res | [
"def",
"call_alert",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"dict",
"(",
")",
"devices",
"=",
"_get_lights",
"(",
")",
"for",
"dev_id",
"in",
"'id'",
"not",
"in",
"kwargs",
"and",
"sorted",
"(",
"devices",
".",
"keys",
"("... | Lamp alert
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **on**: Turns on or off an alert. Default is True.
CLI Example:
.. code-block:: bash
salt '*' hue.alert
salt '*' hue.alert id=1
salt '*' hue.alert id=1,2,3 on=false | [
"Lamp",
"alert"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L344-L367 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_color | def call_color(*args, **kwargs):
'''
Set a color to the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **color**: Fixed color. Values are: red, green, blue, orange, pink, white,
yellow, daylight, purple. Default white.
* **transition**: Transition 0~200.
Advanced:
* **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation.
More: http://www.developers.meethue.com/documentation/hue-xy-values
CLI Example:
.. code-block:: bash
salt '*' hue.color
salt '*' hue.color id=1
salt '*' hue.color id=1,2,3 oolor=red transition=30
salt '*' hue.color id=1 gamut=0.3,0.5
'''
res = dict()
colormap = {
'red': Const.COLOR_RED,
'green': Const.COLOR_GREEN,
'blue': Const.COLOR_BLUE,
'orange': Const.COLOR_ORANGE,
'pink': Const.COLOR_PINK,
'white': Const.COLOR_WHITE,
'yellow': Const.COLOR_YELLOW,
'daylight': Const.COLOR_DAYLIGHT,
'purple': Const.COLOR_PURPLE,
}
devices = _get_lights()
color = kwargs.get("gamut")
if color:
color = color.split(",")
if len(color) == 2:
try:
color = {"xy": [float(color[0]), float(color[1])]}
except Exception as ex:
color = None
else:
color = None
if not color:
color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE)
color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)})
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, color)
return res | python | def call_color(*args, **kwargs):
'''
Set a color to the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **color**: Fixed color. Values are: red, green, blue, orange, pink, white,
yellow, daylight, purple. Default white.
* **transition**: Transition 0~200.
Advanced:
* **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation.
More: http://www.developers.meethue.com/documentation/hue-xy-values
CLI Example:
.. code-block:: bash
salt '*' hue.color
salt '*' hue.color id=1
salt '*' hue.color id=1,2,3 oolor=red transition=30
salt '*' hue.color id=1 gamut=0.3,0.5
'''
res = dict()
colormap = {
'red': Const.COLOR_RED,
'green': Const.COLOR_GREEN,
'blue': Const.COLOR_BLUE,
'orange': Const.COLOR_ORANGE,
'pink': Const.COLOR_PINK,
'white': Const.COLOR_WHITE,
'yellow': Const.COLOR_YELLOW,
'daylight': Const.COLOR_DAYLIGHT,
'purple': Const.COLOR_PURPLE,
}
devices = _get_lights()
color = kwargs.get("gamut")
if color:
color = color.split(",")
if len(color) == 2:
try:
color = {"xy": [float(color[0]), float(color[1])]}
except Exception as ex:
color = None
else:
color = None
if not color:
color = colormap.get(kwargs.get("color", 'white'), Const.COLOR_WHITE)
color.update({"transitiontime": max(min(kwargs.get("transition", 0), 200), 0)})
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, color)
return res | [
"def",
"call_color",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"dict",
"(",
")",
"colormap",
"=",
"{",
"'red'",
":",
"Const",
".",
"COLOR_RED",
",",
"'green'",
":",
"Const",
".",
"COLOR_GREEN",
",",
"'blue'",
":",
"Const",
".... | Set a color to the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **color**: Fixed color. Values are: red, green, blue, orange, pink, white,
yellow, daylight, purple. Default white.
* **transition**: Transition 0~200.
Advanced:
* **gamut**: XY coordinates. Use gamut according to the Philips HUE devices documentation.
More: http://www.developers.meethue.com/documentation/hue-xy-values
CLI Example:
.. code-block:: bash
salt '*' hue.color
salt '*' hue.color id=1
salt '*' hue.color id=1,2,3 oolor=red transition=30
salt '*' hue.color id=1 gamut=0.3,0.5 | [
"Set",
"a",
"color",
"to",
"the",
"lamp",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L396-L454 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_brightness | def call_brightness(*args, **kwargs):
'''
Set an effect to the lamp.
Arguments:
* **value**: 0~255 brightness of the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **transition**: Transition 0~200. Default 0.
CLI Example:
.. code-block:: bash
salt '*' hue.brightness value=100
salt '*' hue.brightness id=1 value=150
salt '*' hue.brightness id=1,2,3 value=255
'''
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' is missing")
try:
brightness = max(min(int(kwargs['value']), 244), 1)
except Exception as err:
raise CommandExecutionError("Parameter 'value' does not contains an integer")
try:
transition = max(min(int(kwargs['transition']), 200), 0)
except Exception as err:
transition = 0
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition})
return res | python | def call_brightness(*args, **kwargs):
'''
Set an effect to the lamp.
Arguments:
* **value**: 0~255 brightness of the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **transition**: Transition 0~200. Default 0.
CLI Example:
.. code-block:: bash
salt '*' hue.brightness value=100
salt '*' hue.brightness id=1 value=150
salt '*' hue.brightness id=1,2,3 value=255
'''
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' is missing")
try:
brightness = max(min(int(kwargs['value']), 244), 1)
except Exception as err:
raise CommandExecutionError("Parameter 'value' does not contains an integer")
try:
transition = max(min(int(kwargs['transition']), 200), 0)
except Exception as err:
transition = 0
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"bri": brightness, "transitiontime": transition})
return res | [
"def",
"call_brightness",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"dict",
"(",
")",
"if",
"'value'",
"not",
"in",
"kwargs",
":",
"raise",
"CommandExecutionError",
"(",
"\"Parameter 'value' is missing\"",
")",
"try",
":",
"brightness"... | Set an effect to the lamp.
Arguments:
* **value**: 0~255 brightness of the lamp.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
* **transition**: Transition 0~200. Default 0.
CLI Example:
.. code-block:: bash
salt '*' hue.brightness value=100
salt '*' hue.brightness id=1 value=150
salt '*' hue.brightness id=1,2,3 value=255 | [
"Set",
"an",
"effect",
"to",
"the",
"lamp",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L457-L497 | train |
saltstack/salt | salt/proxy/philips_hue.py | call_temperature | def call_temperature(*args, **kwargs):
'''
Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired
Arguments:
* **value**: 150~500.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.temperature value=150
salt '*' hue.temperature value=150 id=1
salt '*' hue.temperature value=150 id=1,2,3
'''
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' (150~500) is missing")
try:
value = max(min(int(kwargs['value']), 500), 150)
except Exception as err:
raise CommandExecutionError("Parameter 'value' does not contains an integer")
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"ct": value})
return res | python | def call_temperature(*args, **kwargs):
'''
Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired
Arguments:
* **value**: 150~500.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.temperature value=150
salt '*' hue.temperature value=150 id=1
salt '*' hue.temperature value=150 id=1,2,3
'''
res = dict()
if 'value' not in kwargs:
raise CommandExecutionError("Parameter 'value' (150~500) is missing")
try:
value = max(min(int(kwargs['value']), 500), 150)
except Exception as err:
raise CommandExecutionError("Parameter 'value' does not contains an integer")
devices = _get_lights()
for dev_id in 'id' not in kwargs and sorted(devices.keys()) or _get_devices(kwargs):
res[dev_id] = _set(dev_id, {"ct": value})
return res | [
"def",
"call_temperature",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"res",
"=",
"dict",
"(",
")",
"if",
"'value'",
"not",
"in",
"kwargs",
":",
"raise",
"CommandExecutionError",
"(",
"\"Parameter 'value' (150~500) is missing\"",
")",
"try",
":",
"... | Set the mired color temperature. More: http://en.wikipedia.org/wiki/Mired
Arguments:
* **value**: 150~500.
Options:
* **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted.
CLI Example:
.. code-block:: bash
salt '*' hue.temperature value=150
salt '*' hue.temperature value=150 id=1
salt '*' hue.temperature value=150 id=1,2,3 | [
"Set",
"the",
"mired",
"color",
"temperature",
".",
"More",
":",
"http",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Mired"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/philips_hue.py#L500-L533 | train |
saltstack/salt | salt/fileserver/hgfs.py | _get_branch | def _get_branch(repo, name):
'''
Find the requested branch in the specified repo
'''
try:
return [x for x in _all_branches(repo) if x[0] == name][0]
except IndexError:
return False | python | def _get_branch(repo, name):
'''
Find the requested branch in the specified repo
'''
try:
return [x for x in _all_branches(repo) if x[0] == name][0]
except IndexError:
return False | [
"def",
"_get_branch",
"(",
"repo",
",",
"name",
")",
":",
"try",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"_all_branches",
"(",
"repo",
")",
"if",
"x",
"[",
"0",
"]",
"==",
"name",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"return",
"Fal... | Find the requested branch in the specified repo | [
"Find",
"the",
"requested",
"branch",
"in",
"the",
"specified",
"repo"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L111-L118 | train |
saltstack/salt | salt/fileserver/hgfs.py | _get_bookmark | def _get_bookmark(repo, name):
'''
Find the requested bookmark in the specified repo
'''
try:
return [x for x in _all_bookmarks(repo) if x[0] == name][0]
except IndexError:
return False | python | def _get_bookmark(repo, name):
'''
Find the requested bookmark in the specified repo
'''
try:
return [x for x in _all_bookmarks(repo) if x[0] == name][0]
except IndexError:
return False | [
"def",
"_get_bookmark",
"(",
"repo",
",",
"name",
")",
":",
"try",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"_all_bookmarks",
"(",
"repo",
")",
"if",
"x",
"[",
"0",
"]",
"==",
"name",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"return",
"... | Find the requested bookmark in the specified repo | [
"Find",
"the",
"requested",
"bookmark",
"in",
"the",
"specified",
"repo"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L132-L139 | train |
saltstack/salt | salt/fileserver/hgfs.py | _get_tag | def _get_tag(repo, name):
'''
Find the requested tag in the specified repo
'''
try:
return [x for x in _all_tags(repo) if x[0] == name][0]
except IndexError:
return False | python | def _get_tag(repo, name):
'''
Find the requested tag in the specified repo
'''
try:
return [x for x in _all_tags(repo) if x[0] == name][0]
except IndexError:
return False | [
"def",
"_get_tag",
"(",
"repo",
",",
"name",
")",
":",
"try",
":",
"return",
"[",
"x",
"for",
"x",
"in",
"_all_tags",
"(",
"repo",
")",
"if",
"x",
"[",
"0",
"]",
"==",
"name",
"]",
"[",
"0",
"]",
"except",
"IndexError",
":",
"return",
"False"
] | Find the requested tag in the specified repo | [
"Find",
"the",
"requested",
"tag",
"in",
"the",
"specified",
"repo"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L154-L161 | train |
saltstack/salt | salt/fileserver/hgfs.py | _get_ref | def _get_ref(repo, name):
'''
Return ref tuple if ref is in the repo.
'''
if name == 'base':
name = repo['base']
if name == repo['base'] or name in envs():
if repo['branch_method'] == 'branches':
return _get_branch(repo['repo'], name) \
or _get_tag(repo['repo'], name)
elif repo['branch_method'] == 'bookmarks':
return _get_bookmark(repo['repo'], name) \
or _get_tag(repo['repo'], name)
elif repo['branch_method'] == 'mixed':
return _get_branch(repo['repo'], name) \
or _get_bookmark(repo['repo'], name) \
or _get_tag(repo['repo'], name)
return False | python | def _get_ref(repo, name):
'''
Return ref tuple if ref is in the repo.
'''
if name == 'base':
name = repo['base']
if name == repo['base'] or name in envs():
if repo['branch_method'] == 'branches':
return _get_branch(repo['repo'], name) \
or _get_tag(repo['repo'], name)
elif repo['branch_method'] == 'bookmarks':
return _get_bookmark(repo['repo'], name) \
or _get_tag(repo['repo'], name)
elif repo['branch_method'] == 'mixed':
return _get_branch(repo['repo'], name) \
or _get_bookmark(repo['repo'], name) \
or _get_tag(repo['repo'], name)
return False | [
"def",
"_get_ref",
"(",
"repo",
",",
"name",
")",
":",
"if",
"name",
"==",
"'base'",
":",
"name",
"=",
"repo",
"[",
"'base'",
"]",
"if",
"name",
"==",
"repo",
"[",
"'base'",
"]",
"or",
"name",
"in",
"envs",
"(",
")",
":",
"if",
"repo",
"[",
"'b... | Return ref tuple if ref is in the repo. | [
"Return",
"ref",
"tuple",
"if",
"ref",
"is",
"in",
"the",
"repo",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L164-L181 | train |
saltstack/salt | salt/fileserver/hgfs.py | init | def init():
'''
Return a list of hglib objects for the various hgfs remotes
'''
bp_ = os.path.join(__opts__['cachedir'], 'hgfs')
new_remote = False
repos = []
per_remote_defaults = {}
for param in PER_REMOTE_OVERRIDES:
per_remote_defaults[param] = \
six.text_type(__opts__['hgfs_{0}'.format(param)])
for remote in __opts__['hgfs_remotes']:
repo_conf = copy.deepcopy(per_remote_defaults)
if isinstance(remote, dict):
repo_url = next(iter(remote))
per_remote_conf = dict(
[(key, six.text_type(val)) for key, val in
six.iteritems(salt.utils.data.repack_dictlist(remote[repo_url]))]
)
if not per_remote_conf:
log.error(
'Invalid per-remote configuration for hgfs remote %s. If '
'no per-remote parameters are being specified, there may '
'be a trailing colon after the URL, which should be '
'removed. Check the master configuration file.', repo_url
)
_failhard()
branch_method = \
per_remote_conf.get('branch_method',
per_remote_defaults['branch_method'])
if branch_method not in VALID_BRANCH_METHODS:
log.error(
'Invalid branch_method \'%s\' for remote %s. Valid '
'branch methods are: %s. This remote will be ignored.',
branch_method, repo_url, ', '.join(VALID_BRANCH_METHODS)
)
_failhard()
per_remote_errors = False
for param in (x for x in per_remote_conf
if x not in PER_REMOTE_OVERRIDES):
log.error(
'Invalid configuration parameter \'%s\' for remote %s. '
'Valid parameters are: %s. See the documentation for '
'further information.',
param, repo_url, ', '.join(PER_REMOTE_OVERRIDES)
)
per_remote_errors = True
if per_remote_errors:
_failhard()
repo_conf.update(per_remote_conf)
else:
repo_url = remote
if not isinstance(repo_url, six.string_types):
log.error(
'Invalid hgfs remote %s. Remotes must be strings, you may '
'need to enclose the URL in quotes', repo_url
)
_failhard()
try:
repo_conf['mountpoint'] = salt.utils.url.strip_proto(
repo_conf['mountpoint']
)
except TypeError:
# mountpoint not specified
pass
hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5'))
repo_hash = hash_type(repo_url).hexdigest()
rp_ = os.path.join(bp_, repo_hash)
if not os.path.isdir(rp_):
os.makedirs(rp_)
if not os.listdir(rp_):
# Only init if the directory is empty.
hglib.init(rp_)
new_remote = True
try:
repo = hglib.open(rp_)
except hglib.error.ServerError:
log.error(
'Cache path %s (corresponding remote: %s) exists but is not '
'a valid mercurial repository. You will need to manually '
'delete this directory on the master to continue to use this '
'hgfs remote.', rp_, repo_url
)
_failhard()
except Exception as exc:
log.error(
'Exception \'%s\' encountered while initializing hgfs '
'remote %s', exc, repo_url
)
_failhard()
try:
refs = repo.config(names='paths')
except hglib.error.CommandError:
refs = None
# Do NOT put this if statement inside the except block above. Earlier
# versions of hglib did not raise an exception, so we need to do it
# this way to support both older and newer hglib.
if not refs:
# Write an hgrc defining the remote URL
hgconfpath = os.path.join(rp_, '.hg', 'hgrc')
with salt.utils.files.fopen(hgconfpath, 'w+') as hgconfig:
hgconfig.write('[paths]\n')
hgconfig.write(
salt.utils.stringutils.to_str(
'default = {0}\n'.format(repo_url)
)
)
repo_conf.update({
'repo': repo,
'url': repo_url,
'hash': repo_hash,
'cachedir': rp_,
'lockfile': os.path.join(__opts__['cachedir'],
'hgfs',
'{0}.update.lk'.format(repo_hash))
})
repos.append(repo_conf)
repo.close()
if new_remote:
remote_map = os.path.join(__opts__['cachedir'], 'hgfs/remote_map.txt')
try:
with salt.utils.files.fopen(remote_map, 'w+') as fp_:
timestamp = datetime.now().strftime('%d %b %Y %H:%M:%S.%f')
fp_.write('# hgfs_remote map as of {0}\n'.format(timestamp))
for repo in repos:
fp_.write(
salt.utils.stringutils.to_str(
'{0} = {1}\n'.format(repo['hash'], repo['url'])
)
)
except OSError:
pass
else:
log.info('Wrote new hgfs_remote map to %s', remote_map)
return repos | python | def init():
'''
Return a list of hglib objects for the various hgfs remotes
'''
bp_ = os.path.join(__opts__['cachedir'], 'hgfs')
new_remote = False
repos = []
per_remote_defaults = {}
for param in PER_REMOTE_OVERRIDES:
per_remote_defaults[param] = \
six.text_type(__opts__['hgfs_{0}'.format(param)])
for remote in __opts__['hgfs_remotes']:
repo_conf = copy.deepcopy(per_remote_defaults)
if isinstance(remote, dict):
repo_url = next(iter(remote))
per_remote_conf = dict(
[(key, six.text_type(val)) for key, val in
six.iteritems(salt.utils.data.repack_dictlist(remote[repo_url]))]
)
if not per_remote_conf:
log.error(
'Invalid per-remote configuration for hgfs remote %s. If '
'no per-remote parameters are being specified, there may '
'be a trailing colon after the URL, which should be '
'removed. Check the master configuration file.', repo_url
)
_failhard()
branch_method = \
per_remote_conf.get('branch_method',
per_remote_defaults['branch_method'])
if branch_method not in VALID_BRANCH_METHODS:
log.error(
'Invalid branch_method \'%s\' for remote %s. Valid '
'branch methods are: %s. This remote will be ignored.',
branch_method, repo_url, ', '.join(VALID_BRANCH_METHODS)
)
_failhard()
per_remote_errors = False
for param in (x for x in per_remote_conf
if x not in PER_REMOTE_OVERRIDES):
log.error(
'Invalid configuration parameter \'%s\' for remote %s. '
'Valid parameters are: %s. See the documentation for '
'further information.',
param, repo_url, ', '.join(PER_REMOTE_OVERRIDES)
)
per_remote_errors = True
if per_remote_errors:
_failhard()
repo_conf.update(per_remote_conf)
else:
repo_url = remote
if not isinstance(repo_url, six.string_types):
log.error(
'Invalid hgfs remote %s. Remotes must be strings, you may '
'need to enclose the URL in quotes', repo_url
)
_failhard()
try:
repo_conf['mountpoint'] = salt.utils.url.strip_proto(
repo_conf['mountpoint']
)
except TypeError:
# mountpoint not specified
pass
hash_type = getattr(hashlib, __opts__.get('hash_type', 'md5'))
repo_hash = hash_type(repo_url).hexdigest()
rp_ = os.path.join(bp_, repo_hash)
if not os.path.isdir(rp_):
os.makedirs(rp_)
if not os.listdir(rp_):
# Only init if the directory is empty.
hglib.init(rp_)
new_remote = True
try:
repo = hglib.open(rp_)
except hglib.error.ServerError:
log.error(
'Cache path %s (corresponding remote: %s) exists but is not '
'a valid mercurial repository. You will need to manually '
'delete this directory on the master to continue to use this '
'hgfs remote.', rp_, repo_url
)
_failhard()
except Exception as exc:
log.error(
'Exception \'%s\' encountered while initializing hgfs '
'remote %s', exc, repo_url
)
_failhard()
try:
refs = repo.config(names='paths')
except hglib.error.CommandError:
refs = None
# Do NOT put this if statement inside the except block above. Earlier
# versions of hglib did not raise an exception, so we need to do it
# this way to support both older and newer hglib.
if not refs:
# Write an hgrc defining the remote URL
hgconfpath = os.path.join(rp_, '.hg', 'hgrc')
with salt.utils.files.fopen(hgconfpath, 'w+') as hgconfig:
hgconfig.write('[paths]\n')
hgconfig.write(
salt.utils.stringutils.to_str(
'default = {0}\n'.format(repo_url)
)
)
repo_conf.update({
'repo': repo,
'url': repo_url,
'hash': repo_hash,
'cachedir': rp_,
'lockfile': os.path.join(__opts__['cachedir'],
'hgfs',
'{0}.update.lk'.format(repo_hash))
})
repos.append(repo_conf)
repo.close()
if new_remote:
remote_map = os.path.join(__opts__['cachedir'], 'hgfs/remote_map.txt')
try:
with salt.utils.files.fopen(remote_map, 'w+') as fp_:
timestamp = datetime.now().strftime('%d %b %Y %H:%M:%S.%f')
fp_.write('# hgfs_remote map as of {0}\n'.format(timestamp))
for repo in repos:
fp_.write(
salt.utils.stringutils.to_str(
'{0} = {1}\n'.format(repo['hash'], repo['url'])
)
)
except OSError:
pass
else:
log.info('Wrote new hgfs_remote map to %s', remote_map)
return repos | [
"def",
"init",
"(",
")",
":",
"bp_",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'hgfs'",
")",
"new_remote",
"=",
"False",
"repos",
"=",
"[",
"]",
"per_remote_defaults",
"=",
"{",
"}",
"for",
"param",
"in",
"... | Return a list of hglib objects for the various hgfs remotes | [
"Return",
"a",
"list",
"of",
"hglib",
"objects",
"for",
"the",
"various",
"hgfs",
"remotes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L193-L341 | train |
saltstack/salt | salt/fileserver/hgfs.py | lock | def lock(remote=None):
'''
Place an update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked.
'''
def _do_lock(repo):
success = []
failed = []
if not os.path.exists(repo['lockfile']):
try:
with salt.utils.files.fopen(repo['lockfile'], 'w'):
pass
except (IOError, OSError) as exc:
msg = ('Unable to set update lock for {0} ({1}): {2} '
.format(repo['url'], repo['lockfile'], exc))
log.debug(msg)
failed.append(msg)
else:
msg = 'Set lock for {0}'.format(repo['url'])
log.debug(msg)
success.append(msg)
return success, failed
if isinstance(remote, dict):
return _do_lock(remote)
locked = []
errors = []
for repo in init():
if remote:
try:
if not fnmatch.fnmatch(repo['url'], remote):
continue
except TypeError:
# remote was non-string, try again
if not fnmatch.fnmatch(repo['url'], six.text_type(remote)):
continue
success, failed = _do_lock(repo)
locked.extend(success)
errors.extend(failed)
return locked, errors | python | def lock(remote=None):
'''
Place an update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked.
'''
def _do_lock(repo):
success = []
failed = []
if not os.path.exists(repo['lockfile']):
try:
with salt.utils.files.fopen(repo['lockfile'], 'w'):
pass
except (IOError, OSError) as exc:
msg = ('Unable to set update lock for {0} ({1}): {2} '
.format(repo['url'], repo['lockfile'], exc))
log.debug(msg)
failed.append(msg)
else:
msg = 'Set lock for {0}'.format(repo['url'])
log.debug(msg)
success.append(msg)
return success, failed
if isinstance(remote, dict):
return _do_lock(remote)
locked = []
errors = []
for repo in init():
if remote:
try:
if not fnmatch.fnmatch(repo['url'], remote):
continue
except TypeError:
# remote was non-string, try again
if not fnmatch.fnmatch(repo['url'], six.text_type(remote)):
continue
success, failed = _do_lock(repo)
locked.extend(success)
errors.extend(failed)
return locked, errors | [
"def",
"lock",
"(",
"remote",
"=",
"None",
")",
":",
"def",
"_do_lock",
"(",
"repo",
")",
":",
"success",
"=",
"[",
"]",
"failed",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"repo",
"[",
"'lockfile'",
"]",
")",
":",
"try... | Place an update.lk
``remote`` can either be a dictionary containing repo configuration
information, or a pattern. If the latter, then remotes for which the URL
matches the pattern will be locked. | [
"Place",
"an",
"update",
".",
"lk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L457-L501 | train |
saltstack/salt | salt/fileserver/hgfs.py | update | def update():
'''
Execute an hg pull on all of the repos
'''
# data for the fileserver event
data = {'changed': False,
'backend': 'hgfs'}
# _clear_old_remotes runs init(), so use the value from there to avoid a
# second init()
data['changed'], repos = _clear_old_remotes()
for repo in repos:
if os.path.exists(repo['lockfile']):
log.warning(
'Update lockfile is present for hgfs remote %s, skipping. '
'If this warning persists, it is possible that the update '
'process was interrupted. Removing %s or running '
'\'salt-run fileserver.clear_lock hgfs\' will allow updates '
'to continue for this remote.', repo['url'], repo['lockfile']
)
continue
_, errors = lock(repo)
if errors:
log.error(
'Unable to set update lock for hgfs remote %s, skipping.',
repo['url']
)
continue
log.debug('hgfs is fetching from %s', repo['url'])
repo['repo'].open()
curtip = repo['repo'].tip()
try:
repo['repo'].pull()
except Exception as exc:
log.error(
'Exception %s caught while updating hgfs remote %s',
exc, repo['url'], exc_info_on_loglevel=logging.DEBUG
)
else:
newtip = repo['repo'].tip()
if curtip[1] != newtip[1]:
data['changed'] = True
repo['repo'].close()
clear_lock(repo)
env_cache = os.path.join(__opts__['cachedir'], 'hgfs/envs.p')
if data.get('changed', False) is True or not os.path.isfile(env_cache):
env_cachedir = os.path.dirname(env_cache)
if not os.path.exists(env_cachedir):
os.makedirs(env_cachedir)
new_envs = envs(ignore_cache=True)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(env_cache, 'wb+') as fp_:
fp_.write(serial.dumps(new_envs))
log.trace('Wrote env cache data to %s', env_cache)
# if there is a change, fire an event
if __opts__.get('fileserver_events', False):
event = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=False)
event.fire_event(data, tagify(['hgfs', 'update'], prefix='fileserver'))
try:
salt.fileserver.reap_fileserver_cache_dir(
os.path.join(__opts__['cachedir'], 'hgfs/hash'),
find_file
)
except (IOError, OSError):
# Hash file won't exist if no files have yet been served up
pass | python | def update():
'''
Execute an hg pull on all of the repos
'''
# data for the fileserver event
data = {'changed': False,
'backend': 'hgfs'}
# _clear_old_remotes runs init(), so use the value from there to avoid a
# second init()
data['changed'], repos = _clear_old_remotes()
for repo in repos:
if os.path.exists(repo['lockfile']):
log.warning(
'Update lockfile is present for hgfs remote %s, skipping. '
'If this warning persists, it is possible that the update '
'process was interrupted. Removing %s or running '
'\'salt-run fileserver.clear_lock hgfs\' will allow updates '
'to continue for this remote.', repo['url'], repo['lockfile']
)
continue
_, errors = lock(repo)
if errors:
log.error(
'Unable to set update lock for hgfs remote %s, skipping.',
repo['url']
)
continue
log.debug('hgfs is fetching from %s', repo['url'])
repo['repo'].open()
curtip = repo['repo'].tip()
try:
repo['repo'].pull()
except Exception as exc:
log.error(
'Exception %s caught while updating hgfs remote %s',
exc, repo['url'], exc_info_on_loglevel=logging.DEBUG
)
else:
newtip = repo['repo'].tip()
if curtip[1] != newtip[1]:
data['changed'] = True
repo['repo'].close()
clear_lock(repo)
env_cache = os.path.join(__opts__['cachedir'], 'hgfs/envs.p')
if data.get('changed', False) is True or not os.path.isfile(env_cache):
env_cachedir = os.path.dirname(env_cache)
if not os.path.exists(env_cachedir):
os.makedirs(env_cachedir)
new_envs = envs(ignore_cache=True)
serial = salt.payload.Serial(__opts__)
with salt.utils.files.fopen(env_cache, 'wb+') as fp_:
fp_.write(serial.dumps(new_envs))
log.trace('Wrote env cache data to %s', env_cache)
# if there is a change, fire an event
if __opts__.get('fileserver_events', False):
event = salt.utils.event.get_event(
'master',
__opts__['sock_dir'],
__opts__['transport'],
opts=__opts__,
listen=False)
event.fire_event(data, tagify(['hgfs', 'update'], prefix='fileserver'))
try:
salt.fileserver.reap_fileserver_cache_dir(
os.path.join(__opts__['cachedir'], 'hgfs/hash'),
find_file
)
except (IOError, OSError):
# Hash file won't exist if no files have yet been served up
pass | [
"def",
"update",
"(",
")",
":",
"# data for the fileserver event",
"data",
"=",
"{",
"'changed'",
":",
"False",
",",
"'backend'",
":",
"'hgfs'",
"}",
"# _clear_old_remotes runs init(), so use the value from there to avoid a",
"# second init()",
"data",
"[",
"'changed'",
"... | Execute an hg pull on all of the repos | [
"Execute",
"an",
"hg",
"pull",
"on",
"all",
"of",
"the",
"repos"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L504-L575 | train |
saltstack/salt | salt/fileserver/hgfs.py | envs | def envs(ignore_cache=False):
'''
Return a list of refs that can be used as environments
'''
if not ignore_cache:
env_cache = os.path.join(__opts__['cachedir'], 'hgfs/envs.p')
cache_match = salt.fileserver.check_env_cache(__opts__, env_cache)
if cache_match is not None:
return cache_match
ret = set()
for repo in init():
repo['repo'].open()
if repo['branch_method'] in ('branches', 'mixed'):
for branch in _all_branches(repo['repo']):
branch_name = branch[0]
if branch_name == repo['base']:
branch_name = 'base'
ret.add(branch_name)
if repo['branch_method'] in ('bookmarks', 'mixed'):
for bookmark in _all_bookmarks(repo['repo']):
bookmark_name = bookmark[0]
if bookmark_name == repo['base']:
bookmark_name = 'base'
ret.add(bookmark_name)
ret.update([x[0] for x in _all_tags(repo['repo'])])
repo['repo'].close()
return [x for x in sorted(ret) if _env_is_exposed(x)] | python | def envs(ignore_cache=False):
'''
Return a list of refs that can be used as environments
'''
if not ignore_cache:
env_cache = os.path.join(__opts__['cachedir'], 'hgfs/envs.p')
cache_match = salt.fileserver.check_env_cache(__opts__, env_cache)
if cache_match is not None:
return cache_match
ret = set()
for repo in init():
repo['repo'].open()
if repo['branch_method'] in ('branches', 'mixed'):
for branch in _all_branches(repo['repo']):
branch_name = branch[0]
if branch_name == repo['base']:
branch_name = 'base'
ret.add(branch_name)
if repo['branch_method'] in ('bookmarks', 'mixed'):
for bookmark in _all_bookmarks(repo['repo']):
bookmark_name = bookmark[0]
if bookmark_name == repo['base']:
bookmark_name = 'base'
ret.add(bookmark_name)
ret.update([x[0] for x in _all_tags(repo['repo'])])
repo['repo'].close()
return [x for x in sorted(ret) if _env_is_exposed(x)] | [
"def",
"envs",
"(",
"ignore_cache",
"=",
"False",
")",
":",
"if",
"not",
"ignore_cache",
":",
"env_cache",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'hgfs/envs.p'",
")",
"cache_match",
"=",
"salt",
".",
"fileserv... | Return a list of refs that can be used as environments | [
"Return",
"a",
"list",
"of",
"refs",
"that",
"can",
"be",
"used",
"as",
"environments"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L610-L636 | train |
saltstack/salt | salt/fileserver/hgfs.py | find_file | def find_file(path, tgt_env='base', **kwargs): # pylint: disable=W0613
'''
Find the first file to match the path and ref, read the file out of hg
and send the path to the newly cached file
'''
fnd = {'path': '',
'rel': ''}
if os.path.isabs(path) or tgt_env not in envs():
return fnd
dest = os.path.join(__opts__['cachedir'], 'hgfs/refs', tgt_env, path)
hashes_glob = os.path.join(__opts__['cachedir'],
'hgfs/hash',
tgt_env,
'{0}.hash.*'.format(path))
blobshadest = os.path.join(__opts__['cachedir'],
'hgfs/hash',
tgt_env,
'{0}.hash.blob_sha1'.format(path))
lk_fn = os.path.join(__opts__['cachedir'],
'hgfs/hash',
tgt_env,
'{0}.lk'.format(path))
destdir = os.path.dirname(dest)
hashdir = os.path.dirname(blobshadest)
if not os.path.isdir(destdir):
try:
os.makedirs(destdir)
except OSError:
# Path exists and is a file, remove it and retry
os.remove(destdir)
os.makedirs(destdir)
if not os.path.isdir(hashdir):
try:
os.makedirs(hashdir)
except OSError:
# Path exists and is a file, remove it and retry
os.remove(hashdir)
os.makedirs(hashdir)
for repo in init():
if repo['mountpoint'] \
and not path.startswith(repo['mountpoint'] + os.path.sep):
continue
repo_path = path[len(repo['mountpoint']):].lstrip(os.path.sep)
if repo['root']:
repo_path = os.path.join(repo['root'], repo_path)
repo['repo'].open()
ref = _get_ref(repo, tgt_env)
if not ref:
# Branch or tag not found in repo, try the next
repo['repo'].close()
continue
salt.fileserver.wait_lock(lk_fn, dest)
if os.path.isfile(blobshadest) and os.path.isfile(dest):
with salt.utils.files.fopen(blobshadest, 'r') as fp_:
sha = fp_.read()
if sha == ref[2]:
fnd['rel'] = path
fnd['path'] = dest
repo['repo'].close()
return fnd
try:
repo['repo'].cat(
['path:{0}'.format(repo_path)], rev=ref[2], output=dest
)
except hglib.error.CommandError:
repo['repo'].close()
continue
with salt.utils.files.fopen(lk_fn, 'w'):
pass
for filename in glob.glob(hashes_glob):
try:
os.remove(filename)
except Exception:
pass
with salt.utils.files.fopen(blobshadest, 'w+') as fp_:
fp_.write(ref[2])
try:
os.remove(lk_fn)
except (OSError, IOError):
pass
fnd['rel'] = path
fnd['path'] = dest
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(dest))
except Exception:
pass
repo['repo'].close()
return fnd
return fnd | python | def find_file(path, tgt_env='base', **kwargs): # pylint: disable=W0613
'''
Find the first file to match the path and ref, read the file out of hg
and send the path to the newly cached file
'''
fnd = {'path': '',
'rel': ''}
if os.path.isabs(path) or tgt_env not in envs():
return fnd
dest = os.path.join(__opts__['cachedir'], 'hgfs/refs', tgt_env, path)
hashes_glob = os.path.join(__opts__['cachedir'],
'hgfs/hash',
tgt_env,
'{0}.hash.*'.format(path))
blobshadest = os.path.join(__opts__['cachedir'],
'hgfs/hash',
tgt_env,
'{0}.hash.blob_sha1'.format(path))
lk_fn = os.path.join(__opts__['cachedir'],
'hgfs/hash',
tgt_env,
'{0}.lk'.format(path))
destdir = os.path.dirname(dest)
hashdir = os.path.dirname(blobshadest)
if not os.path.isdir(destdir):
try:
os.makedirs(destdir)
except OSError:
# Path exists and is a file, remove it and retry
os.remove(destdir)
os.makedirs(destdir)
if not os.path.isdir(hashdir):
try:
os.makedirs(hashdir)
except OSError:
# Path exists and is a file, remove it and retry
os.remove(hashdir)
os.makedirs(hashdir)
for repo in init():
if repo['mountpoint'] \
and not path.startswith(repo['mountpoint'] + os.path.sep):
continue
repo_path = path[len(repo['mountpoint']):].lstrip(os.path.sep)
if repo['root']:
repo_path = os.path.join(repo['root'], repo_path)
repo['repo'].open()
ref = _get_ref(repo, tgt_env)
if not ref:
# Branch or tag not found in repo, try the next
repo['repo'].close()
continue
salt.fileserver.wait_lock(lk_fn, dest)
if os.path.isfile(blobshadest) and os.path.isfile(dest):
with salt.utils.files.fopen(blobshadest, 'r') as fp_:
sha = fp_.read()
if sha == ref[2]:
fnd['rel'] = path
fnd['path'] = dest
repo['repo'].close()
return fnd
try:
repo['repo'].cat(
['path:{0}'.format(repo_path)], rev=ref[2], output=dest
)
except hglib.error.CommandError:
repo['repo'].close()
continue
with salt.utils.files.fopen(lk_fn, 'w'):
pass
for filename in glob.glob(hashes_glob):
try:
os.remove(filename)
except Exception:
pass
with salt.utils.files.fopen(blobshadest, 'w+') as fp_:
fp_.write(ref[2])
try:
os.remove(lk_fn)
except (OSError, IOError):
pass
fnd['rel'] = path
fnd['path'] = dest
try:
# Converting the stat result to a list, the elements of the
# list correspond to the following stat_result params:
# 0 => st_mode=33188
# 1 => st_ino=10227377
# 2 => st_dev=65026
# 3 => st_nlink=1
# 4 => st_uid=1000
# 5 => st_gid=1000
# 6 => st_size=1056233
# 7 => st_atime=1468284229
# 8 => st_mtime=1456338235
# 9 => st_ctime=1456338235
fnd['stat'] = list(os.stat(dest))
except Exception:
pass
repo['repo'].close()
return fnd
return fnd | [
"def",
"find_file",
"(",
"path",
",",
"tgt_env",
"=",
"'base'",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=W0613",
"fnd",
"=",
"{",
"'path'",
":",
"''",
",",
"'rel'",
":",
"''",
"}",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")... | Find the first file to match the path and ref, read the file out of hg
and send the path to the newly cached file | [
"Find",
"the",
"first",
"file",
"to",
"match",
"the",
"path",
"and",
"ref",
"read",
"the",
"file",
"out",
"of",
"hg",
"and",
"send",
"the",
"path",
"to",
"the",
"newly",
"cached",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/fileserver/hgfs.py#L639-L742 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.