repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/modules/mac_keychain.py | install | def install(cert,
password,
keychain="/Library/Keychains/System.keychain",
allow_any=False,
keychain_password=None):
'''
Install a certificate
cert
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section.
Note: The password given here will show up as plaintext in the job returned
info.
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
allow_any
Allow any application to access the imported certificate without warning
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.install test.p12 test123
'''
if keychain_password is not None:
unlock_keychain(keychain, keychain_password)
cmd = 'security import {0} -P {1} -k {2}'.format(cert, password, keychain)
if allow_any:
cmd += ' -A'
return __salt__['cmd.run'](cmd) | python | def install(cert,
password,
keychain="/Library/Keychains/System.keychain",
allow_any=False,
keychain_password=None):
'''
Install a certificate
cert
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section.
Note: The password given here will show up as plaintext in the job returned
info.
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
allow_any
Allow any application to access the imported certificate without warning
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.install test.p12 test123
'''
if keychain_password is not None:
unlock_keychain(keychain, keychain_password)
cmd = 'security import {0} -P {1} -k {2}'.format(cert, password, keychain)
if allow_any:
cmd += ' -A'
return __salt__['cmd.run'](cmd) | [
"def",
"install",
"(",
"cert",
",",
"password",
",",
"keychain",
"=",
"\"/Library/Keychains/System.keychain\"",
",",
"allow_any",
"=",
"False",
",",
"keychain_password",
"=",
"None",
")",
":",
"if",
"keychain_password",
"is",
"not",
"None",
":",
"unlock_keychain",... | Install a certificate
cert
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section.
Note: The password given here will show up as plaintext in the job returned
info.
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
allow_any
Allow any application to access the imported certificate without warning
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.install test.p12 test123 | [
"Install",
"a",
"certificate"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L44-L88 | train |
saltstack/salt | salt/modules/mac_keychain.py | uninstall | def uninstall(cert_name,
keychain="/Library/Keychains/System.keychain",
keychain_password=None):
'''
Uninstall a certificate from a keychain
cert_name
The name of the certificate to remove
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.install test.p12 test123
'''
if keychain_password is not None:
unlock_keychain(keychain, keychain_password)
cmd = 'security delete-certificate -c "{0}" {1}'.format(cert_name, keychain)
return __salt__['cmd.run'](cmd) | python | def uninstall(cert_name,
keychain="/Library/Keychains/System.keychain",
keychain_password=None):
'''
Uninstall a certificate from a keychain
cert_name
The name of the certificate to remove
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.install test.p12 test123
'''
if keychain_password is not None:
unlock_keychain(keychain, keychain_password)
cmd = 'security delete-certificate -c "{0}" {1}'.format(cert_name, keychain)
return __salt__['cmd.run'](cmd) | [
"def",
"uninstall",
"(",
"cert_name",
",",
"keychain",
"=",
"\"/Library/Keychains/System.keychain\"",
",",
"keychain_password",
"=",
"None",
")",
":",
"if",
"keychain_password",
"is",
"not",
"None",
":",
"unlock_keychain",
"(",
"keychain",
",",
"keychain_password",
... | Uninstall a certificate from a keychain
cert_name
The name of the certificate to remove
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
keychain_password
If your keychain is likely to be locked pass the password and it will be unlocked
before running the import
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.install test.p12 test123 | [
"Uninstall",
"a",
"certificate",
"from",
"a",
"keychain"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L91-L121 | train |
saltstack/salt | salt/modules/mac_keychain.py | list_certs | def list_certs(keychain="/Library/Keychains/System.keychain"):
'''
List all of the installed certificates
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
CLI Example:
.. code-block:: bash
salt '*' keychain.list_certs
'''
cmd = 'security find-certificate -a {0} | grep -o "alis".*\\" | ' \
'grep -o \'\\"[-A-Za-z0-9.:() ]*\\"\''.format(_quote(keychain))
out = __salt__['cmd.run'](cmd, python_shell=True)
return out.replace('"', '').split('\n') | python | def list_certs(keychain="/Library/Keychains/System.keychain"):
'''
List all of the installed certificates
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
CLI Example:
.. code-block:: bash
salt '*' keychain.list_certs
'''
cmd = 'security find-certificate -a {0} | grep -o "alis".*\\" | ' \
'grep -o \'\\"[-A-Za-z0-9.:() ]*\\"\''.format(_quote(keychain))
out = __salt__['cmd.run'](cmd, python_shell=True)
return out.replace('"', '').split('\n') | [
"def",
"list_certs",
"(",
"keychain",
"=",
"\"/Library/Keychains/System.keychain\"",
")",
":",
"cmd",
"=",
"'security find-certificate -a {0} | grep -o \"alis\".*\\\\\" | '",
"'grep -o \\'\\\\\"[-A-Za-z0-9.:() ]*\\\\\"\\''",
".",
"format",
"(",
"_quote",
"(",
"keychain",
")",
"... | List all of the installed certificates
keychain
The keychain to install the certificate to, this defaults to
/Library/Keychains/System.keychain
CLI Example:
.. code-block:: bash
salt '*' keychain.list_certs | [
"List",
"all",
"of",
"the",
"installed",
"certificates"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L124-L141 | train |
saltstack/salt | salt/modules/mac_keychain.py | get_friendly_name | def get_friendly_name(cert, password):
'''
Get the friendly name of the given certificate
cert
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.get_friendly_name /tmp/test.p12 test123
'''
cmd = 'openssl pkcs12 -in {0} -passin pass:{1} -info -nodes -nokeys 2> /dev/null | ' \
'grep friendlyName:'.format(_quote(cert), _quote(password))
out = __salt__['cmd.run'](cmd, python_shell=True)
return out.replace("friendlyName: ", "").strip() | python | def get_friendly_name(cert, password):
'''
Get the friendly name of the given certificate
cert
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.get_friendly_name /tmp/test.p12 test123
'''
cmd = 'openssl pkcs12 -in {0} -passin pass:{1} -info -nodes -nokeys 2> /dev/null | ' \
'grep friendlyName:'.format(_quote(cert), _quote(password))
out = __salt__['cmd.run'](cmd, python_shell=True)
return out.replace("friendlyName: ", "").strip() | [
"def",
"get_friendly_name",
"(",
"cert",
",",
"password",
")",
":",
"cmd",
"=",
"'openssl pkcs12 -in {0} -passin pass:{1} -info -nodes -nokeys 2> /dev/null | '",
"'grep friendlyName:'",
".",
"format",
"(",
"_quote",
"(",
"cert",
")",
",",
"_quote",
"(",
"password",
")",... | Get the friendly name of the given certificate
cert
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the PASS PHRASE ARGUMENTS section
Note: The password given here will show up as plaintext in the returned job
info.
CLI Example:
.. code-block:: bash
salt '*' keychain.get_friendly_name /tmp/test.p12 test123 | [
"Get",
"the",
"friendly",
"name",
"of",
"the",
"given",
"certificate"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L144-L167 | train |
saltstack/salt | salt/modules/mac_keychain.py | get_default_keychain | def get_default_keychain(user=None, domain="user"):
'''
Get the default keychain
user
The user to check the default keychain of
domain
The domain to use valid values are user|system|common|dynamic, the default is user
CLI Example:
.. code-block:: bash
salt '*' keychain.get_default_keychain
'''
cmd = "security default-keychain -d {0}".format(domain)
return __salt__['cmd.run'](cmd, runas=user) | python | def get_default_keychain(user=None, domain="user"):
'''
Get the default keychain
user
The user to check the default keychain of
domain
The domain to use valid values are user|system|common|dynamic, the default is user
CLI Example:
.. code-block:: bash
salt '*' keychain.get_default_keychain
'''
cmd = "security default-keychain -d {0}".format(domain)
return __salt__['cmd.run'](cmd, runas=user) | [
"def",
"get_default_keychain",
"(",
"user",
"=",
"None",
",",
"domain",
"=",
"\"user\"",
")",
":",
"cmd",
"=",
"\"security default-keychain -d {0}\"",
".",
"format",
"(",
"domain",
")",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"runas",
"... | Get the default keychain
user
The user to check the default keychain of
domain
The domain to use valid values are user|system|common|dynamic, the default is user
CLI Example:
.. code-block:: bash
salt '*' keychain.get_default_keychain | [
"Get",
"the",
"default",
"keychain"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L170-L187 | train |
saltstack/salt | salt/modules/mac_keychain.py | set_default_keychain | def set_default_keychain(keychain, domain="user", user=None):
'''
Set the default keychain
keychain
The location of the keychain to set as default
domain
The domain to use valid values are user|system|common|dynamic, the default is user
user
The user to set the default keychain as
CLI Example:
.. code-block:: bash
salt '*' keychain.set_keychain /Users/fred/Library/Keychains/login.keychain
'''
cmd = "security default-keychain -d {0} -s {1}".format(domain, keychain)
return __salt__['cmd.run'](cmd, runas=user) | python | def set_default_keychain(keychain, domain="user", user=None):
'''
Set the default keychain
keychain
The location of the keychain to set as default
domain
The domain to use valid values are user|system|common|dynamic, the default is user
user
The user to set the default keychain as
CLI Example:
.. code-block:: bash
salt '*' keychain.set_keychain /Users/fred/Library/Keychains/login.keychain
'''
cmd = "security default-keychain -d {0} -s {1}".format(domain, keychain)
return __salt__['cmd.run'](cmd, runas=user) | [
"def",
"set_default_keychain",
"(",
"keychain",
",",
"domain",
"=",
"\"user\"",
",",
"user",
"=",
"None",
")",
":",
"cmd",
"=",
"\"security default-keychain -d {0} -s {1}\"",
".",
"format",
"(",
"domain",
",",
"keychain",
")",
"return",
"__salt__",
"[",
"'cmd.ru... | Set the default keychain
keychain
The location of the keychain to set as default
domain
The domain to use valid values are user|system|common|dynamic, the default is user
user
The user to set the default keychain as
CLI Example:
.. code-block:: bash
salt '*' keychain.set_keychain /Users/fred/Library/Keychains/login.keychain | [
"Set",
"the",
"default",
"keychain"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L190-L210 | train |
saltstack/salt | salt/modules/mac_keychain.py | get_hash | def get_hash(name, password=None):
'''
Returns the hash of a certificate in the keychain.
name
The name of the certificate (which you can get from keychain.get_friendly_name) or the
location of a p12 file.
password
The password that is used in the certificate. Only required if your passing a p12 file.
Note: This will be outputted to logs
CLI Example:
.. code-block:: bash
salt '*' keychain.get_hash /tmp/test.p12 test123
'''
if '.p12' in name[-4:]:
cmd = 'openssl pkcs12 -in {0} -passin pass:{1} -passout pass:{1}'.format(name, password)
else:
cmd = 'security find-certificate -c "{0}" -m -p'.format(name)
out = __salt__['cmd.run'](cmd)
matches = re.search('-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE-----', out, re.DOTALL | re.MULTILINE)
if matches:
return matches.group(1)
else:
return False | python | def get_hash(name, password=None):
'''
Returns the hash of a certificate in the keychain.
name
The name of the certificate (which you can get from keychain.get_friendly_name) or the
location of a p12 file.
password
The password that is used in the certificate. Only required if your passing a p12 file.
Note: This will be outputted to logs
CLI Example:
.. code-block:: bash
salt '*' keychain.get_hash /tmp/test.p12 test123
'''
if '.p12' in name[-4:]:
cmd = 'openssl pkcs12 -in {0} -passin pass:{1} -passout pass:{1}'.format(name, password)
else:
cmd = 'security find-certificate -c "{0}" -m -p'.format(name)
out = __salt__['cmd.run'](cmd)
matches = re.search('-----BEGIN CERTIFICATE-----(.*)-----END CERTIFICATE-----', out, re.DOTALL | re.MULTILINE)
if matches:
return matches.group(1)
else:
return False | [
"def",
"get_hash",
"(",
"name",
",",
"password",
"=",
"None",
")",
":",
"if",
"'.p12'",
"in",
"name",
"[",
"-",
"4",
":",
"]",
":",
"cmd",
"=",
"'openssl pkcs12 -in {0} -passin pass:{1} -passout pass:{1}'",
".",
"format",
"(",
"name",
",",
"password",
")",
... | Returns the hash of a certificate in the keychain.
name
The name of the certificate (which you can get from keychain.get_friendly_name) or the
location of a p12 file.
password
The password that is used in the certificate. Only required if your passing a p12 file.
Note: This will be outputted to logs
CLI Example:
.. code-block:: bash
salt '*' keychain.get_hash /tmp/test.p12 test123 | [
"Returns",
"the",
"hash",
"of",
"a",
"certificate",
"in",
"the",
"keychain",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_keychain.py#L236-L265 | train |
saltstack/salt | salt/states/aws_sqs.py | exists | def exists(
name,
region,
user=None,
opts=False):
'''
Ensure the SQS queue exists.
name
Name of the SQS queue.
region
Region to create the queue
user
Name of the user performing the SQS operations
opts
Include additional arguments and options to the aws command line
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
does_exist = __salt__['aws_sqs.queue_exists'](name, region, opts, user)
if not does_exist:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'AWS SQS queue {0} is set to be created'.format(
name)
return ret
created = __salt__['aws_sqs.create_queue'](name, region, opts, user)
if created['retcode'] == 0:
ret['changes']['new'] = created['stdout']
else:
ret['result'] = False
ret['comment'] = created['stderr']
else:
ret['comment'] = '{0} exists in {1}'.format(name, region)
return ret | python | def exists(
name,
region,
user=None,
opts=False):
'''
Ensure the SQS queue exists.
name
Name of the SQS queue.
region
Region to create the queue
user
Name of the user performing the SQS operations
opts
Include additional arguments and options to the aws command line
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
does_exist = __salt__['aws_sqs.queue_exists'](name, region, opts, user)
if not does_exist:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'AWS SQS queue {0} is set to be created'.format(
name)
return ret
created = __salt__['aws_sqs.create_queue'](name, region, opts, user)
if created['retcode'] == 0:
ret['changes']['new'] = created['stdout']
else:
ret['result'] = False
ret['comment'] = created['stderr']
else:
ret['comment'] = '{0} exists in {1}'.format(name, region)
return ret | [
"def",
"exists",
"(",
"name",
",",
"region",
",",
"user",
"=",
"None",
",",
"opts",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
... | Ensure the SQS queue exists.
name
Name of the SQS queue.
region
Region to create the queue
user
Name of the user performing the SQS operations
opts
Include additional arguments and options to the aws command line | [
"Ensure",
"the",
"SQS",
"queue",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/aws_sqs.py#L30-L70 | train |
saltstack/salt | salt/states/aws_sqs.py | absent | def absent(
name,
region,
user=None,
opts=False):
'''
Remove the named SQS queue if it exists.
name
Name of the SQS queue.
region
Region to remove the queue from
user
Name of the user performing the SQS operations
opts
Include additional arguments and options to the aws command line
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
does_exist = __salt__['aws_sqs.queue_exists'](name, region, opts, user)
if does_exist:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'AWS SQS queue {0} is set to be removed'.format(
name)
return ret
removed = __salt__['aws_sqs.delete_queue'](name, region, opts, user)
if removed['retcode'] == 0:
ret['changes']['removed'] = removed['stdout']
else:
ret['result'] = False
ret['comment'] = removed['stderr']
else:
ret['comment'] = '{0} does not exist in {1}'.format(name, region)
return ret | python | def absent(
name,
region,
user=None,
opts=False):
'''
Remove the named SQS queue if it exists.
name
Name of the SQS queue.
region
Region to remove the queue from
user
Name of the user performing the SQS operations
opts
Include additional arguments and options to the aws command line
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
does_exist = __salt__['aws_sqs.queue_exists'](name, region, opts, user)
if does_exist:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'AWS SQS queue {0} is set to be removed'.format(
name)
return ret
removed = __salt__['aws_sqs.delete_queue'](name, region, opts, user)
if removed['retcode'] == 0:
ret['changes']['removed'] = removed['stdout']
else:
ret['result'] = False
ret['comment'] = removed['stderr']
else:
ret['comment'] = '{0} does not exist in {1}'.format(name, region)
return ret | [
"def",
"absent",
"(",
"name",
",",
"region",
",",
"user",
"=",
"None",
",",
"opts",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
... | Remove the named SQS queue if it exists.
name
Name of the SQS queue.
region
Region to remove the queue from
user
Name of the user performing the SQS operations
opts
Include additional arguments and options to the aws command line | [
"Remove",
"the",
"named",
"SQS",
"queue",
"if",
"it",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/aws_sqs.py#L73-L112 | train |
saltstack/salt | setup.py | _parse_op | def _parse_op(op):
'''
>>> _parse_op('>')
'gt'
>>> _parse_op('>=')
'ge'
>>> _parse_op('=>')
'ge'
>>> _parse_op('=> ')
'ge'
>>> _parse_op('<')
'lt'
>>> _parse_op('<=')
'le'
>>> _parse_op('==')
'eq'
>>> _parse_op(' <= ')
'le'
'''
op = op.strip()
if '>' in op:
if '=' in op:
return 'ge'
else:
return 'gt'
elif '<' in op:
if '=' in op:
return 'le'
else:
return 'lt'
elif '!' in op:
return 'ne'
else:
return 'eq' | python | def _parse_op(op):
'''
>>> _parse_op('>')
'gt'
>>> _parse_op('>=')
'ge'
>>> _parse_op('=>')
'ge'
>>> _parse_op('=> ')
'ge'
>>> _parse_op('<')
'lt'
>>> _parse_op('<=')
'le'
>>> _parse_op('==')
'eq'
>>> _parse_op(' <= ')
'le'
'''
op = op.strip()
if '>' in op:
if '=' in op:
return 'ge'
else:
return 'gt'
elif '<' in op:
if '=' in op:
return 'le'
else:
return 'lt'
elif '!' in op:
return 'ne'
else:
return 'eq' | [
"def",
"_parse_op",
"(",
"op",
")",
":",
"op",
"=",
"op",
".",
"strip",
"(",
")",
"if",
"'>'",
"in",
"op",
":",
"if",
"'='",
"in",
"op",
":",
"return",
"'ge'",
"else",
":",
"return",
"'gt'",
"elif",
"'<'",
"in",
"op",
":",
"if",
"'='",
"in",
... | >>> _parse_op('>')
'gt'
>>> _parse_op('>=')
'ge'
>>> _parse_op('=>')
'ge'
>>> _parse_op('=> ')
'ge'
>>> _parse_op('<')
'lt'
>>> _parse_op('<=')
'le'
>>> _parse_op('==')
'eq'
>>> _parse_op(' <= ')
'le' | [
">>>",
"_parse_op",
"(",
">",
")",
"gt",
">>>",
"_parse_op",
"(",
">",
"=",
")",
"ge",
">>>",
"_parse_op",
"(",
"=",
">",
")",
"ge",
">>>",
"_parse_op",
"(",
"=",
">",
")",
"ge",
">>>",
"_parse_op",
"(",
"<",
")",
"lt",
">>>",
"_parse_op",
"(",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/setup.py#L142-L175 | train |
saltstack/salt | setup.py | _parse_ver | def _parse_ver(ver):
'''
>>> _parse_ver("'3.4' # pyzmq 17.1.0 stopped building wheels for python3.4")
'3.4'
>>> _parse_ver('"3.4"')
'3.4'
>>> _parse_ver('"2.6.17"')
'2.6.17'
'''
if '#' in ver:
ver, _ = ver.split('#', 1)
ver = ver.strip()
return ver.strip('\'').strip('"') | python | def _parse_ver(ver):
'''
>>> _parse_ver("'3.4' # pyzmq 17.1.0 stopped building wheels for python3.4")
'3.4'
>>> _parse_ver('"3.4"')
'3.4'
>>> _parse_ver('"2.6.17"')
'2.6.17'
'''
if '#' in ver:
ver, _ = ver.split('#', 1)
ver = ver.strip()
return ver.strip('\'').strip('"') | [
"def",
"_parse_ver",
"(",
"ver",
")",
":",
"if",
"'#'",
"in",
"ver",
":",
"ver",
",",
"_",
"=",
"ver",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"ver",
"=",
"ver",
".",
"strip",
"(",
")",
"return",
"ver",
".",
"strip",
"(",
"'\\''",
")",
".",
... | >>> _parse_ver("'3.4' # pyzmq 17.1.0 stopped building wheels for python3.4")
'3.4'
>>> _parse_ver('"3.4"')
'3.4'
>>> _parse_ver('"2.6.17"')
'2.6.17' | [
">>>",
"_parse_ver",
"(",
"3",
".",
"4",
"#",
"pyzmq",
"17",
".",
"1",
".",
"0",
"stopped",
"building",
"wheels",
"for",
"python3",
".",
"4",
")",
"3",
".",
"4",
">>>",
"_parse_ver",
"(",
"3",
".",
"4",
")",
"3",
".",
"4",
">>>",
"_parse_ver",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/setup.py#L178-L190 | train |
saltstack/salt | setup.py | _check_ver | def _check_ver(pyver, op, wanted):
'''
>>> _check_ver('2.7.15', 'gt', '2.7')
True
>>> _check_ver('2.7.15', 'gt', '2.7.15')
False
>>> _check_ver('2.7.15', 'ge', '2.7.15')
True
>>> _check_ver('2.7.15', 'eq', '2.7.15')
True
'''
pyver = distutils.version.LooseVersion(pyver)
wanted = distutils.version.LooseVersion(wanted)
return getattr(operator, '__{}__'.format(op))(pyver, wanted) | python | def _check_ver(pyver, op, wanted):
'''
>>> _check_ver('2.7.15', 'gt', '2.7')
True
>>> _check_ver('2.7.15', 'gt', '2.7.15')
False
>>> _check_ver('2.7.15', 'ge', '2.7.15')
True
>>> _check_ver('2.7.15', 'eq', '2.7.15')
True
'''
pyver = distutils.version.LooseVersion(pyver)
wanted = distutils.version.LooseVersion(wanted)
return getattr(operator, '__{}__'.format(op))(pyver, wanted) | [
"def",
"_check_ver",
"(",
"pyver",
",",
"op",
",",
"wanted",
")",
":",
"pyver",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"pyver",
")",
"wanted",
"=",
"distutils",
".",
"version",
".",
"LooseVersion",
"(",
"wanted",
")",
"return",
"geta... | >>> _check_ver('2.7.15', 'gt', '2.7')
True
>>> _check_ver('2.7.15', 'gt', '2.7.15')
False
>>> _check_ver('2.7.15', 'ge', '2.7.15')
True
>>> _check_ver('2.7.15', 'eq', '2.7.15')
True | [
">>>",
"_check_ver",
"(",
"2",
".",
"7",
".",
"15",
"gt",
"2",
".",
"7",
")",
"True",
">>>",
"_check_ver",
"(",
"2",
".",
"7",
".",
"15",
"gt",
"2",
".",
"7",
".",
"15",
")",
"False",
">>>",
"_check_ver",
"(",
"2",
".",
"7",
".",
"15",
"ge"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/setup.py#L193-L206 | train |
saltstack/salt | salt/modules/mac_portspkg.py | list_pkgs | def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# 'removed', 'purge_desired' not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
cmd = ['port', 'installed']
out = salt.utils.mac_utils.execute_return_result(cmd)
for line in out.splitlines():
try:
name, version_num, active = re.split(r'\s+', line.lstrip())[0:3]
version_num = version_num[1:]
except ValueError:
continue
if not LIST_ACTIVE_ONLY or active == '(active)':
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret | python | def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# 'removed', 'purge_desired' not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x))
for x in ('removed', 'purge_desired')]):
return {}
if 'pkg.list_pkgs' in __context__:
if versions_as_list:
return __context__['pkg.list_pkgs']
else:
ret = copy.deepcopy(__context__['pkg.list_pkgs'])
__salt__['pkg_resource.stringify'](ret)
return ret
ret = {}
cmd = ['port', 'installed']
out = salt.utils.mac_utils.execute_return_result(cmd)
for line in out.splitlines():
try:
name, version_num, active = re.split(r'\s+', line.lstrip())[0:3]
version_num = version_num[1:]
except ValueError:
continue
if not LIST_ACTIVE_ONLY or active == '(active)':
__salt__['pkg_resource.add_pkg'](ret, name, version_num)
__salt__['pkg_resource.sort_pkglist'](ret)
__context__['pkg.list_pkgs'] = copy.deepcopy(ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"versions_as_list",
")",
"# 'removed', 'purge_desired' not yet implemented or not applicable"... | List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs | [
"List",
"the",
"packages",
"currently",
"installed",
"in",
"a",
"dict",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_portspkg.py#L87-L129 | train |
saltstack/salt | salt/modules/mac_portspkg.py | remove | def remove(name=None, pkgs=None, **kwargs):
'''
Removes packages with ``port uninstall``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
cmd = ['port', 'uninstall']
cmd.extend(targets)
err_message = ''
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
err_message = exc.strerror
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if err_message:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': err_message, 'changes': ret})
return ret | python | def remove(name=None, pkgs=None, **kwargs):
'''
Removes packages with ``port uninstall``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
cmd = ['port', 'uninstall']
cmd.extend(targets)
err_message = ''
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
err_message = exc.strerror
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if err_message:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': err_message, 'changes': ret})
return ret | [
"def",
"remove",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pkg_params",
"=",
"__salt__",
"[",
"'pkg_resource.parse_targets'",
"]",
"(",
"name",
",",
"pkgs",
",",
"*",
"*",
"kwargs",
")",
"[",
"0",
"]",
... | Removes packages with ``port uninstall``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]' | [
"Removes",
"packages",
"with",
"port",
"uninstall",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_portspkg.py#L187-L240 | train |
saltstack/salt | salt/modules/mac_portspkg.py | install | def install(name=None, refresh=False, pkgs=None, **kwargs):
'''
Install the passed package(s) with ``port install``
name
The name of the formula to be installed. Note that this parameter is
ignored if "pkgs" is passed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
version
Specify a version to pkg to install. Ignored if pkgs is specified.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
salt '*' pkg.install git-core version='1.8.5.5'
variant
Specify a variant to pkg to install. Ignored if pkgs is specified.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
salt '*' pkg.install git-core version='1.8.5.5' variant='+credential_osxkeychain+doc+pcre'
Multiple Package Installation Options:
pkgs
A list of formulas to install. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo","bar"]'
salt '*' pkg.install pkgs='["foo@1.2","bar"]'
salt '*' pkg.install pkgs='["foo@1.2+ssl","bar@2.3"]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install 'package package package'
'''
pkg_params, pkg_type = \
__salt__['pkg_resource.parse_targets'](name, pkgs, {})
if salt.utils.data.is_true(refresh):
refresh_db()
# Handle version kwarg for a single package target
if pkgs is None:
version_num = kwargs.get('version')
variant_spec = kwargs.get('variant')
spec = {}
if version_num:
spec['version'] = version_num
if variant_spec:
spec['variant'] = variant_spec
pkg_params = {name: spec}
if not pkg_params:
return {}
formulas_array = []
for pname, pparams in six.iteritems(pkg_params):
formulas_array.append(pname)
if pparams:
if 'version' in pparams:
formulas_array.append('@' + pparams['version'])
if 'variant' in pparams:
formulas_array.append(pparams['variant'])
old = list_pkgs()
cmd = ['port', 'install']
cmd.extend(formulas_array)
err_message = ''
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
err_message = exc.strerror
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if err_message:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': err_message, 'changes': ret})
return ret | python | def install(name=None, refresh=False, pkgs=None, **kwargs):
'''
Install the passed package(s) with ``port install``
name
The name of the formula to be installed. Note that this parameter is
ignored if "pkgs" is passed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
version
Specify a version to pkg to install. Ignored if pkgs is specified.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
salt '*' pkg.install git-core version='1.8.5.5'
variant
Specify a variant to pkg to install. Ignored if pkgs is specified.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
salt '*' pkg.install git-core version='1.8.5.5' variant='+credential_osxkeychain+doc+pcre'
Multiple Package Installation Options:
pkgs
A list of formulas to install. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo","bar"]'
salt '*' pkg.install pkgs='["foo@1.2","bar"]'
salt '*' pkg.install pkgs='["foo@1.2+ssl","bar@2.3"]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install 'package package package'
'''
pkg_params, pkg_type = \
__salt__['pkg_resource.parse_targets'](name, pkgs, {})
if salt.utils.data.is_true(refresh):
refresh_db()
# Handle version kwarg for a single package target
if pkgs is None:
version_num = kwargs.get('version')
variant_spec = kwargs.get('variant')
spec = {}
if version_num:
spec['version'] = version_num
if variant_spec:
spec['variant'] = variant_spec
pkg_params = {name: spec}
if not pkg_params:
return {}
formulas_array = []
for pname, pparams in six.iteritems(pkg_params):
formulas_array.append(pname)
if pparams:
if 'version' in pparams:
formulas_array.append('@' + pparams['version'])
if 'variant' in pparams:
formulas_array.append(pparams['variant'])
old = list_pkgs()
cmd = ['port', 'install']
cmd.extend(formulas_array)
err_message = ''
try:
salt.utils.mac_utils.execute_return_success(cmd)
except CommandExecutionError as exc:
err_message = exc.strerror
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if err_message:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': err_message, 'changes': ret})
return ret | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"pkg_params",
",",
"pkg_type",
"=",
"__salt__",
"[",
"'pkg_resource.parse_targets'",
"]",
"(",
"name",
",",
"pkgs",
"... | Install the passed package(s) with ``port install``
name
The name of the formula to be installed. Note that this parameter is
ignored if "pkgs" is passed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
version
Specify a version to pkg to install. Ignored if pkgs is specified.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
salt '*' pkg.install git-core version='1.8.5.5'
variant
Specify a variant to pkg to install. Ignored if pkgs is specified.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
salt '*' pkg.install git-core version='1.8.5.5' variant='+credential_osxkeychain+doc+pcre'
Multiple Package Installation Options:
pkgs
A list of formulas to install. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo","bar"]'
salt '*' pkg.install pkgs='["foo@1.2","bar"]'
salt '*' pkg.install pkgs='["foo@1.2+ssl","bar@2.3"]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install 'package package package' | [
"Install",
"the",
"passed",
"package",
"(",
"s",
")",
"with",
"port",
"install"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_portspkg.py#L243-L355 | train |
saltstack/salt | salt/modules/mac_portspkg.py | refresh_db | def refresh_db(**kwargs):
'''
Update ports with ``port selfupdate``
CLI Example:
.. code-block:: bash
salt mac pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
cmd = ['port', 'selfupdate']
return salt.utils.mac_utils.execute_return_success(cmd) | python | def refresh_db(**kwargs):
'''
Update ports with ``port selfupdate``
CLI Example:
.. code-block:: bash
salt mac pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
cmd = ['port', 'selfupdate']
return salt.utils.mac_utils.execute_return_success(cmd) | [
"def",
"refresh_db",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Remove rtag file to keep multiple refreshes from happening in pkg states",
"salt",
".",
"utils",
".",
"pkg",
".",
"clear_rtag",
"(",
"__opts__",
")",
"cmd",
"=",
"[",
"'port'",
",",
"'selfupdate'",
"]",
"r... | Update ports with ``port selfupdate``
CLI Example:
.. code-block:: bash
salt mac pkg.refresh_db | [
"Update",
"ports",
"with",
"port",
"selfupdate"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_portspkg.py#L392-L405 | train |
saltstack/salt | salt/modules/sdb.py | set_ | def set_(uri, value):
'''
Set a value in a db, using a uri in the form of ``sdb://<profile>/<key>``.
If the uri provided does not start with ``sdb://`` or the value is not
successfully set, return ``False``.
CLI Example:
.. code-block:: bash
salt '*' sdb.set sdb://mymemcached/foo bar
'''
return salt.utils.sdb.sdb_set(uri, value, __opts__, __utils__) | python | def set_(uri, value):
'''
Set a value in a db, using a uri in the form of ``sdb://<profile>/<key>``.
If the uri provided does not start with ``sdb://`` or the value is not
successfully set, return ``False``.
CLI Example:
.. code-block:: bash
salt '*' sdb.set sdb://mymemcached/foo bar
'''
return salt.utils.sdb.sdb_set(uri, value, __opts__, __utils__) | [
"def",
"set_",
"(",
"uri",
",",
"value",
")",
":",
"return",
"salt",
".",
"utils",
".",
"sdb",
".",
"sdb_set",
"(",
"uri",
",",
"value",
",",
"__opts__",
",",
"__utils__",
")"
] | Set a value in a db, using a uri in the form of ``sdb://<profile>/<key>``.
If the uri provided does not start with ``sdb://`` or the value is not
successfully set, return ``False``.
CLI Example:
.. code-block:: bash
salt '*' sdb.set sdb://mymemcached/foo bar | [
"Set",
"a",
"value",
"in",
"a",
"db",
"using",
"a",
"uri",
"in",
"the",
"form",
"of",
"sdb",
":",
"//",
"<profile",
">",
"/",
"<key",
">",
".",
"If",
"the",
"uri",
"provided",
"does",
"not",
"start",
"with",
"sdb",
":",
"//",
"or",
"the",
"value"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sdb.py#L31-L43 | train |
saltstack/salt | salt/modules/sdb.py | get_or_set_hash | def get_or_set_hash(uri,
length=8,
chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'):
'''
Perform a one-time generation of a hash and write it to sdb.
If that value has already been set return the value instead.
This is useful for generating passwords or keys that are specific to
multiple minions that need to be stored somewhere centrally.
State Example:
.. code-block:: yaml
some_mysql_user:
mysql_user:
- present
- host: localhost
- password: '{{ salt['sdb.get_or_set_hash']('some_mysql_user_pass') }}'
CLI Example:
.. code-block:: bash
salt '*' sdb.get_or_set_hash 'SECRET_KEY' 50
.. warning::
This function could return strings which may contain characters which are reserved
as directives by the YAML parser, such as strings beginning with ``%``. To avoid
issues when using the output of this function in an SLS file containing YAML+Jinja,
surround the call with single quotes.
'''
return salt.utils.sdb.sdb_get_or_set_hash(uri, __opts__, length, chars, __utils__) | python | def get_or_set_hash(uri,
length=8,
chars='abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'):
'''
Perform a one-time generation of a hash and write it to sdb.
If that value has already been set return the value instead.
This is useful for generating passwords or keys that are specific to
multiple minions that need to be stored somewhere centrally.
State Example:
.. code-block:: yaml
some_mysql_user:
mysql_user:
- present
- host: localhost
- password: '{{ salt['sdb.get_or_set_hash']('some_mysql_user_pass') }}'
CLI Example:
.. code-block:: bash
salt '*' sdb.get_or_set_hash 'SECRET_KEY' 50
.. warning::
This function could return strings which may contain characters which are reserved
as directives by the YAML parser, such as strings beginning with ``%``. To avoid
issues when using the output of this function in an SLS file containing YAML+Jinja,
surround the call with single quotes.
'''
return salt.utils.sdb.sdb_get_or_set_hash(uri, __opts__, length, chars, __utils__) | [
"def",
"get_or_set_hash",
"(",
"uri",
",",
"length",
"=",
"8",
",",
"chars",
"=",
"'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'",
")",
":",
"return",
"salt",
".",
"utils",
".",
"sdb",
".",
"sdb_get_or_set_hash",
"(",
"uri",
",",
"__opts__",
",",
"length"... | Perform a one-time generation of a hash and write it to sdb.
If that value has already been set return the value instead.
This is useful for generating passwords or keys that are specific to
multiple minions that need to be stored somewhere centrally.
State Example:
.. code-block:: yaml
some_mysql_user:
mysql_user:
- present
- host: localhost
- password: '{{ salt['sdb.get_or_set_hash']('some_mysql_user_pass') }}'
CLI Example:
.. code-block:: bash
salt '*' sdb.get_or_set_hash 'SECRET_KEY' 50
.. warning::
This function could return strings which may contain characters which are reserved
as directives by the YAML parser, such as strings beginning with ``%``. To avoid
issues when using the output of this function in an SLS file containing YAML+Jinja,
surround the call with single quotes. | [
"Perform",
"a",
"one",
"-",
"time",
"generation",
"of",
"a",
"hash",
"and",
"write",
"it",
"to",
"sdb",
".",
"If",
"that",
"value",
"has",
"already",
"been",
"set",
"return",
"the",
"value",
"instead",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sdb.py#L61-L94 | train |
saltstack/salt | salt/modules/csf.py | _temp_exists | def _temp_exists(method, ip):
'''
Checks if the ip exists as a temporary rule based
on the method supplied, (tempallow, tempdeny).
'''
_type = method.replace('temp', '').upper()
cmd = "csf -t | awk -v code=1 -v type=_type -v ip=ip '$1==type && $2==ip {{code=0}} END {{exit code}}'".format(_type=_type, ip=ip)
exists = __salt__['cmd.run_all'](cmd)
return not bool(exists['retcode']) | python | def _temp_exists(method, ip):
'''
Checks if the ip exists as a temporary rule based
on the method supplied, (tempallow, tempdeny).
'''
_type = method.replace('temp', '').upper()
cmd = "csf -t | awk -v code=1 -v type=_type -v ip=ip '$1==type && $2==ip {{code=0}} END {{exit code}}'".format(_type=_type, ip=ip)
exists = __salt__['cmd.run_all'](cmd)
return not bool(exists['retcode']) | [
"def",
"_temp_exists",
"(",
"method",
",",
"ip",
")",
":",
"_type",
"=",
"method",
".",
"replace",
"(",
"'temp'",
",",
"''",
")",
".",
"upper",
"(",
")",
"cmd",
"=",
"\"csf -t | awk -v code=1 -v type=_type -v ip=ip '$1==type && $2==ip {{code=0}} END {{exit code}}'\"",... | Checks if the ip exists as a temporary rule based
on the method supplied, (tempallow, tempdeny). | [
"Checks",
"if",
"the",
"ip",
"exists",
"as",
"a",
"temporary",
"rule",
"based",
"on",
"the",
"method",
"supplied",
"(",
"tempallow",
"tempdeny",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L31-L39 | train |
saltstack/salt | salt/modules/csf.py | exists | def exists(method,
ip,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
ttl=None,
comment=''):
'''
Returns true a rule for the ip already exists
based on the method supplied. Returns false if
not found.
CLI Example:
.. code-block:: bash
salt '*' csf.exists allow 1.2.3.4
salt '*' csf.exists tempdeny 1.2.3.4
'''
if method.startswith('temp'):
return _temp_exists(method, ip)
if port:
rule = _build_port_rule(ip, port, proto, direction, port_origin, ip_origin, comment)
return _exists_with_port(method, rule)
exists = __salt__['cmd.run_all']("egrep ^'{0} +' /etc/csf/csf.{1}".format(ip, method))
return not bool(exists['retcode']) | python | def exists(method,
ip,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
ttl=None,
comment=''):
'''
Returns true a rule for the ip already exists
based on the method supplied. Returns false if
not found.
CLI Example:
.. code-block:: bash
salt '*' csf.exists allow 1.2.3.4
salt '*' csf.exists tempdeny 1.2.3.4
'''
if method.startswith('temp'):
return _temp_exists(method, ip)
if port:
rule = _build_port_rule(ip, port, proto, direction, port_origin, ip_origin, comment)
return _exists_with_port(method, rule)
exists = __salt__['cmd.run_all']("egrep ^'{0} +' /etc/csf/csf.{1}".format(ip, method))
return not bool(exists['retcode']) | [
"def",
"exists",
"(",
"method",
",",
"ip",
",",
"port",
"=",
"None",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
",",
"port_origin",
"=",
"'d'",
",",
"ip_origin",
"=",
"'d'",
",",
"ttl",
"=",
"None",
",",
"comment",
"=",
"''",
")",
... | Returns true a rule for the ip already exists
based on the method supplied. Returns false if
not found.
CLI Example:
.. code-block:: bash
salt '*' csf.exists allow 1.2.3.4
salt '*' csf.exists tempdeny 1.2.3.4 | [
"Returns",
"true",
"a",
"rule",
"for",
"the",
"ip",
"already",
"exists",
"based",
"on",
"the",
"method",
"supplied",
".",
"Returns",
"false",
"if",
"not",
"found",
".",
"CLI",
"Example",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L47-L73 | train |
saltstack/salt | salt/modules/csf.py | __csf_cmd | def __csf_cmd(cmd):
'''
Execute csf command
'''
csf_cmd = '{0} {1}'.format(salt.utils.path.which('csf'), cmd)
out = __salt__['cmd.run_all'](csf_cmd)
if out['retcode'] != 0:
if not out['stderr']:
ret = out['stdout']
else:
ret = out['stderr']
raise CommandExecutionError(
'csf failed: {0}'.format(ret)
)
else:
ret = out['stdout']
return ret | python | def __csf_cmd(cmd):
'''
Execute csf command
'''
csf_cmd = '{0} {1}'.format(salt.utils.path.which('csf'), cmd)
out = __salt__['cmd.run_all'](csf_cmd)
if out['retcode'] != 0:
if not out['stderr']:
ret = out['stdout']
else:
ret = out['stderr']
raise CommandExecutionError(
'csf failed: {0}'.format(ret)
)
else:
ret = out['stdout']
return ret | [
"def",
"__csf_cmd",
"(",
"cmd",
")",
":",
"csf_cmd",
"=",
"'{0} {1}'",
".",
"format",
"(",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'csf'",
")",
",",
"cmd",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"csf_cmd",
")",
... | Execute csf command | [
"Execute",
"csf",
"command"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L76-L93 | train |
saltstack/salt | salt/modules/csf.py | _build_args | def _build_args(method, ip, comment):
'''
Returns the cmd args for csf basic allow/deny commands.
'''
opt = _get_opt(method)
args = '{0} {1}'.format(opt, ip)
if comment:
args += ' {0}'.format(comment)
return args | python | def _build_args(method, ip, comment):
'''
Returns the cmd args for csf basic allow/deny commands.
'''
opt = _get_opt(method)
args = '{0} {1}'.format(opt, ip)
if comment:
args += ' {0}'.format(comment)
return args | [
"def",
"_build_args",
"(",
"method",
",",
"ip",
",",
"comment",
")",
":",
"opt",
"=",
"_get_opt",
"(",
"method",
")",
"args",
"=",
"'{0} {1}'",
".",
"format",
"(",
"opt",
",",
"ip",
")",
"if",
"comment",
":",
"args",
"+=",
"' {0}'",
".",
"format",
... | Returns the cmd args for csf basic allow/deny commands. | [
"Returns",
"the",
"cmd",
"args",
"for",
"csf",
"basic",
"allow",
"/",
"deny",
"commands",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L121-L129 | train |
saltstack/salt | salt/modules/csf.py | _access_rule | def _access_rule(method,
ip=None,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
comment=''):
'''
Handles the cmd execution for allow and deny commands.
'''
if _status_csf():
if ip is None:
return {'error': 'You must supply an ip address or CIDR.'}
if port is None:
args = _build_args(method, ip, comment)
return __csf_cmd(args)
else:
if method not in ['allow', 'deny']:
return {'error': 'Only allow and deny rules are allowed when specifying a port.'}
return _access_rule_with_port(method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment=comment) | python | def _access_rule(method,
ip=None,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
comment=''):
'''
Handles the cmd execution for allow and deny commands.
'''
if _status_csf():
if ip is None:
return {'error': 'You must supply an ip address or CIDR.'}
if port is None:
args = _build_args(method, ip, comment)
return __csf_cmd(args)
else:
if method not in ['allow', 'deny']:
return {'error': 'Only allow and deny rules are allowed when specifying a port.'}
return _access_rule_with_port(method=method,
ip=ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment=comment) | [
"def",
"_access_rule",
"(",
"method",
",",
"ip",
"=",
"None",
",",
"port",
"=",
"None",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
",",
"port_origin",
"=",
"'d'",
",",
"ip_origin",
"=",
"'d'",
",",
"comment",
"=",
"''",
")",
":",
"i... | Handles the cmd execution for allow and deny commands. | [
"Handles",
"the",
"cmd",
"execution",
"for",
"allow",
"and",
"deny",
"commands",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L132-L159 | train |
saltstack/salt | salt/modules/csf.py | _csf_to_list | def _csf_to_list(option):
'''
Extract comma-separated values from a csf.conf
option and return a list.
'''
result = []
line = get_option(option)
if line:
csv = line.split('=')[1].replace(' ', '').replace('"', '')
result = csv.split(',')
return result | python | def _csf_to_list(option):
'''
Extract comma-separated values from a csf.conf
option and return a list.
'''
result = []
line = get_option(option)
if line:
csv = line.split('=')[1].replace(' ', '').replace('"', '')
result = csv.split(',')
return result | [
"def",
"_csf_to_list",
"(",
"option",
")",
":",
"result",
"=",
"[",
"]",
"line",
"=",
"get_option",
"(",
"option",
")",
"if",
"line",
":",
"csv",
"=",
"line",
".",
"split",
"(",
"'='",
")",
"[",
"1",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
... | Extract comma-separated values from a csf.conf
option and return a list. | [
"Extract",
"comma",
"-",
"separated",
"values",
"from",
"a",
"csf",
".",
"conf",
"option",
"and",
"return",
"a",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L204-L214 | train |
saltstack/salt | salt/modules/csf.py | _tmp_access_rule | def _tmp_access_rule(method,
ip=None,
ttl=None,
port=None,
direction='in',
port_origin='d',
ip_origin='d',
comment=''):
'''
Handles the cmd execution for tempdeny and tempallow commands.
'''
if _status_csf():
if ip is None:
return {'error': 'You must supply an ip address or CIDR.'}
if ttl is None:
return {'error': 'You must supply a ttl.'}
args = _build_tmp_access_args(method, ip, ttl, port, direction, comment)
return __csf_cmd(args) | python | def _tmp_access_rule(method,
ip=None,
ttl=None,
port=None,
direction='in',
port_origin='d',
ip_origin='d',
comment=''):
'''
Handles the cmd execution for tempdeny and tempallow commands.
'''
if _status_csf():
if ip is None:
return {'error': 'You must supply an ip address or CIDR.'}
if ttl is None:
return {'error': 'You must supply a ttl.'}
args = _build_tmp_access_args(method, ip, ttl, port, direction, comment)
return __csf_cmd(args) | [
"def",
"_tmp_access_rule",
"(",
"method",
",",
"ip",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"port",
"=",
"None",
",",
"direction",
"=",
"'in'",
",",
"port_origin",
"=",
"'d'",
",",
"ip_origin",
"=",
"'d'",
",",
"comment",
"=",
"''",
")",
":",
"... | Handles the cmd execution for tempdeny and tempallow commands. | [
"Handles",
"the",
"cmd",
"execution",
"for",
"tempdeny",
"and",
"tempallow",
"commands",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L308-L325 | train |
saltstack/salt | salt/modules/csf.py | _build_tmp_access_args | def _build_tmp_access_args(method, ip, ttl, port, direction, comment):
'''
Builds the cmd args for temporary access/deny opts.
'''
opt = _get_opt(method)
args = '{0} {1} {2}'.format(opt, ip, ttl)
if port:
args += ' -p {0}'.format(port)
if direction:
args += ' -d {0}'.format(direction)
if comment:
args += ' #{0}'.format(comment)
return args | python | def _build_tmp_access_args(method, ip, ttl, port, direction, comment):
'''
Builds the cmd args for temporary access/deny opts.
'''
opt = _get_opt(method)
args = '{0} {1} {2}'.format(opt, ip, ttl)
if port:
args += ' -p {0}'.format(port)
if direction:
args += ' -d {0}'.format(direction)
if comment:
args += ' #{0}'.format(comment)
return args | [
"def",
"_build_tmp_access_args",
"(",
"method",
",",
"ip",
",",
"ttl",
",",
"port",
",",
"direction",
",",
"comment",
")",
":",
"opt",
"=",
"_get_opt",
"(",
"method",
")",
"args",
"=",
"'{0} {1} {2}'",
".",
"format",
"(",
"opt",
",",
"ip",
",",
"ttl",
... | Builds the cmd args for temporary access/deny opts. | [
"Builds",
"the",
"cmd",
"args",
"for",
"temporary",
"access",
"/",
"deny",
"opts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L328-L340 | train |
saltstack/salt | salt/modules/csf.py | tempallow | def tempallow(ip=None, ttl=None, port=None, direction=None, comment=''):
'''
Add an rule to the temporary ip allow list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ssh access'
'''
return _tmp_access_rule('tempallow', ip, ttl, port, direction, comment) | python | def tempallow(ip=None, ttl=None, port=None, direction=None, comment=''):
'''
Add an rule to the temporary ip allow list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ssh access'
'''
return _tmp_access_rule('tempallow', ip, ttl, port, direction, comment) | [
"def",
"tempallow",
"(",
"ip",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"port",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"comment",
"=",
"''",
")",
":",
"return",
"_tmp_access_rule",
"(",
"'tempallow'",
",",
"ip",
",",
"ttl",
",",
"port",
... | Add an rule to the temporary ip allow list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ssh access' | [
"Add",
"an",
"rule",
"to",
"the",
"temporary",
"ip",
"allow",
"list",
".",
"See",
":",
"func",
":",
"_access_rule",
".",
"1",
"-",
"Add",
"an",
"IP",
":",
"CLI",
"Example",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L393-L404 | train |
saltstack/salt | salt/modules/csf.py | tempdeny | def tempdeny(ip=None, ttl=None, port=None, direction=None, comment=''):
'''
Add a rule to the temporary ip deny list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempdeny 127.0.0.1 300 port=22 direction='in' comment='# Brute force attempt'
'''
return _tmp_access_rule('tempdeny', ip, ttl, port, direction, comment) | python | def tempdeny(ip=None, ttl=None, port=None, direction=None, comment=''):
'''
Add a rule to the temporary ip deny list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempdeny 127.0.0.1 300 port=22 direction='in' comment='# Brute force attempt'
'''
return _tmp_access_rule('tempdeny', ip, ttl, port, direction, comment) | [
"def",
"tempdeny",
"(",
"ip",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"port",
"=",
"None",
",",
"direction",
"=",
"None",
",",
"comment",
"=",
"''",
")",
":",
"return",
"_tmp_access_rule",
"(",
"'tempdeny'",
",",
"ip",
",",
"ttl",
",",
"port",
"... | Add a rule to the temporary ip deny list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempdeny 127.0.0.1 300 port=22 direction='in' comment='# Brute force attempt' | [
"Add",
"a",
"rule",
"to",
"the",
"temporary",
"ip",
"deny",
"list",
".",
"See",
":",
"func",
":",
"_access_rule",
".",
"1",
"-",
"Add",
"an",
"IP",
":",
"CLI",
"Example",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L407-L418 | train |
saltstack/salt | salt/modules/csf.py | allow | def allow(ip,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
comment=''):
'''
Add an rule to csf allowed hosts
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.allow 127.0.0.1
salt '*' csf.allow 127.0.0.1 comment="Allow localhost"
'''
return _access_rule('allow',
ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment=comment) | python | def allow(ip,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='s',
ttl=None,
comment=''):
'''
Add an rule to csf allowed hosts
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.allow 127.0.0.1
salt '*' csf.allow 127.0.0.1 comment="Allow localhost"
'''
return _access_rule('allow',
ip,
port=port,
proto=proto,
direction=direction,
port_origin=port_origin,
ip_origin=ip_origin,
comment=comment) | [
"def",
"allow",
"(",
"ip",
",",
"port",
"=",
"None",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
",",
"port_origin",
"=",
"'d'",
",",
"ip_origin",
"=",
"'s'",
",",
"ttl",
"=",
"None",
",",
"comment",
"=",
"''",
")",
":",
"return",
... | Add an rule to csf allowed hosts
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.allow 127.0.0.1
salt '*' csf.allow 127.0.0.1 comment="Allow localhost" | [
"Add",
"an",
"rule",
"to",
"csf",
"allowed",
"hosts",
"See",
":",
"func",
":",
"_access_rule",
".",
"1",
"-",
"Add",
"an",
"IP",
":",
"CLI",
"Example",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L421-L447 | train |
saltstack/salt | salt/modules/csf.py | deny | def deny(ip,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
ttl=None,
comment=''):
'''
Add an rule to csf denied hosts
See :func:`_access_rule`.
1- Deny an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.deny 127.0.0.1
salt '*' csf.deny 127.0.0.1 comment="Too localhosty"
'''
return _access_rule('deny', ip, port, proto, direction, port_origin, ip_origin, comment) | python | def deny(ip,
port=None,
proto='tcp',
direction='in',
port_origin='d',
ip_origin='d',
ttl=None,
comment=''):
'''
Add an rule to csf denied hosts
See :func:`_access_rule`.
1- Deny an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.deny 127.0.0.1
salt '*' csf.deny 127.0.0.1 comment="Too localhosty"
'''
return _access_rule('deny', ip, port, proto, direction, port_origin, ip_origin, comment) | [
"def",
"deny",
"(",
"ip",
",",
"port",
"=",
"None",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
",",
"port_origin",
"=",
"'d'",
",",
"ip_origin",
"=",
"'d'",
",",
"ttl",
"=",
"None",
",",
"comment",
"=",
"''",
")",
":",
"return",
"... | Add an rule to csf denied hosts
See :func:`_access_rule`.
1- Deny an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.deny 127.0.0.1
salt '*' csf.deny 127.0.0.1 comment="Too localhosty" | [
"Add",
"an",
"rule",
"to",
"csf",
"denied",
"hosts",
"See",
":",
"func",
":",
"_access_rule",
".",
"1",
"-",
"Deny",
"an",
"IP",
":",
"CLI",
"Example",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L450-L469 | train |
saltstack/salt | salt/modules/csf.py | allow_ports | def allow_ports(ports, proto='tcp', direction='in'):
'''
Fully replace the incoming or outgoing ports
line in the csf.conf file - e.g. TCP_IN, TCP_OUT,
UDP_IN, UDP_OUT, etc.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_ports ports="[22,80,443,4505,4506]" proto='tcp' direction='in'
'''
results = []
ports = set(ports)
ports = list(ports)
proto = proto.upper()
direction = direction.upper()
_validate_direction_and_proto(direction, proto)
ports_csv = ','.join(six.moves.map(six.text_type, ports))
directions = build_directions(direction)
for direction in directions:
result = __salt__['file.replace']('/etc/csf/csf.conf',
pattern='^{0}_{1}(\ +)?\=(\ +)?".*"$'.format(proto, direction), # pylint: disable=W1401
repl='{0}_{1} = "{2}"'.format(proto, direction, ports_csv))
results.append(result)
return results | python | def allow_ports(ports, proto='tcp', direction='in'):
'''
Fully replace the incoming or outgoing ports
line in the csf.conf file - e.g. TCP_IN, TCP_OUT,
UDP_IN, UDP_OUT, etc.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_ports ports="[22,80,443,4505,4506]" proto='tcp' direction='in'
'''
results = []
ports = set(ports)
ports = list(ports)
proto = proto.upper()
direction = direction.upper()
_validate_direction_and_proto(direction, proto)
ports_csv = ','.join(six.moves.map(six.text_type, ports))
directions = build_directions(direction)
for direction in directions:
result = __salt__['file.replace']('/etc/csf/csf.conf',
pattern='^{0}_{1}(\ +)?\=(\ +)?".*"$'.format(proto, direction), # pylint: disable=W1401
repl='{0}_{1} = "{2}"'.format(proto, direction, ports_csv))
results.append(result)
return results | [
"def",
"allow_ports",
"(",
"ports",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
")",
":",
"results",
"=",
"[",
"]",
"ports",
"=",
"set",
"(",
"ports",
")",
"ports",
"=",
"list",
"(",
"ports",
")",
"proto",
"=",
"proto",
".",
"upper",... | Fully replace the incoming or outgoing ports
line in the csf.conf file - e.g. TCP_IN, TCP_OUT,
UDP_IN, UDP_OUT, etc.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_ports ports="[22,80,443,4505,4506]" proto='tcp' direction='in' | [
"Fully",
"replace",
"the",
"incoming",
"or",
"outgoing",
"ports",
"line",
"in",
"the",
"csf",
".",
"conf",
"file",
"-",
"e",
".",
"g",
".",
"TCP_IN",
"TCP_OUT",
"UDP_IN",
"UDP_OUT",
"etc",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L535-L563 | train |
saltstack/salt | salt/modules/csf.py | get_ports | def get_ports(proto='tcp', direction='in'):
'''
Lists ports from csf.conf based on direction and protocol.
e.g. - TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc..
CLI Example:
.. code-block:: bash
salt '*' csf.allow_port 22 proto='tcp' direction='in'
'''
proto = proto.upper()
direction = direction.upper()
results = {}
_validate_direction_and_proto(direction, proto)
directions = build_directions(direction)
for direction in directions:
option = '{0}_{1}'.format(proto, direction)
results[direction] = _csf_to_list(option)
return results | python | def get_ports(proto='tcp', direction='in'):
'''
Lists ports from csf.conf based on direction and protocol.
e.g. - TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc..
CLI Example:
.. code-block:: bash
salt '*' csf.allow_port 22 proto='tcp' direction='in'
'''
proto = proto.upper()
direction = direction.upper()
results = {}
_validate_direction_and_proto(direction, proto)
directions = build_directions(direction)
for direction in directions:
option = '{0}_{1}'.format(proto, direction)
results[direction] = _csf_to_list(option)
return results | [
"def",
"get_ports",
"(",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'in'",
")",
":",
"proto",
"=",
"proto",
".",
"upper",
"(",
")",
"direction",
"=",
"direction",
".",
"upper",
"(",
")",
"results",
"=",
"{",
"}",
"_validate_direction_and_proto",
"(",... | Lists ports from csf.conf based on direction and protocol.
e.g. - TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc..
CLI Example:
.. code-block:: bash
salt '*' csf.allow_port 22 proto='tcp' direction='in' | [
"Lists",
"ports",
"from",
"csf",
".",
"conf",
"based",
"on",
"direction",
"and",
"protocol",
".",
"e",
".",
"g",
".",
"-",
"TCP_IN",
"TCP_OUT",
"UDP_IN",
"UDP_OUT",
"etc",
".."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L566-L587 | train |
saltstack/salt | salt/modules/csf.py | allow_port | def allow_port(port, proto='tcp', direction='both'):
'''
Like allow_ports, but it will append to the
existing entry instead of replacing it.
Takes a single port instead of a list of ports.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_port 22 proto='tcp' direction='in'
'''
ports = get_ports(proto=proto, direction=direction)
direction = direction.upper()
_validate_direction_and_proto(direction, proto)
directions = build_directions(direction)
results = []
for direction in directions:
_ports = ports[direction]
_ports.append(port)
results += allow_ports(_ports, proto=proto, direction=direction)
return results | python | def allow_port(port, proto='tcp', direction='both'):
'''
Like allow_ports, but it will append to the
existing entry instead of replacing it.
Takes a single port instead of a list of ports.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_port 22 proto='tcp' direction='in'
'''
ports = get_ports(proto=proto, direction=direction)
direction = direction.upper()
_validate_direction_and_proto(direction, proto)
directions = build_directions(direction)
results = []
for direction in directions:
_ports = ports[direction]
_ports.append(port)
results += allow_ports(_ports, proto=proto, direction=direction)
return results | [
"def",
"allow_port",
"(",
"port",
",",
"proto",
"=",
"'tcp'",
",",
"direction",
"=",
"'both'",
")",
":",
"ports",
"=",
"get_ports",
"(",
"proto",
"=",
"proto",
",",
"direction",
"=",
"direction",
")",
"direction",
"=",
"direction",
".",
"upper",
"(",
"... | Like allow_ports, but it will append to the
existing entry instead of replacing it.
Takes a single port instead of a list of ports.
CLI Example:
.. code-block:: bash
salt '*' csf.allow_port 22 proto='tcp' direction='in' | [
"Like",
"allow_ports",
"but",
"it",
"will",
"append",
"to",
"the",
"existing",
"entry",
"instead",
"of",
"replacing",
"it",
".",
"Takes",
"a",
"single",
"port",
"instead",
"of",
"a",
"list",
"of",
"ports",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/csf.py#L611-L633 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _ssh_state | def _ssh_state(chunks, st_kwargs,
kwargs, test=False):
'''
Function to run a state with the given chunk via salt-ssh
'''
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
__opts__.get('extra_filerefs', '')
)
)
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'])
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, __opts__['hash_type'])
cmd = 'state.pkg {0}/salt_state.tgz test={1} pkg_sum={2} hash_type={3}'.format(
__opts__['thin_dir'],
test,
trans_tar_sum,
__opts__['hash_type'])
single = salt.client.ssh.Single(
__opts__,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(__opts__['thin_dir']))
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.data.decode(salt.utils.json.loads(stdout, object_hook=salt.utils.data.encode_dict))
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(str(e))
# If for some reason the json load fails, return the stdout
return salt.utils.data.decode(stdout) | python | def _ssh_state(chunks, st_kwargs,
kwargs, test=False):
'''
Function to run a state with the given chunk via salt-ssh
'''
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
__opts__.get('extra_filerefs', '')
)
)
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'])
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, __opts__['hash_type'])
cmd = 'state.pkg {0}/salt_state.tgz test={1} pkg_sum={2} hash_type={3}'.format(
__opts__['thin_dir'],
test,
trans_tar_sum,
__opts__['hash_type'])
single = salt.client.ssh.Single(
__opts__,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(__opts__['thin_dir']))
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.data.decode(salt.utils.json.loads(stdout, object_hook=salt.utils.data.encode_dict))
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(str(e))
# If for some reason the json load fails, return the stdout
return salt.utils.data.decode(stdout) | [
"def",
"_ssh_state",
"(",
"chunks",
",",
"st_kwargs",
",",
"kwargs",
",",
"test",
"=",
"False",
")",
":",
"file_refs",
"=",
"salt",
".",
"client",
".",
"ssh",
".",
"state",
".",
"lowstate_file_refs",
"(",
"chunks",
",",
"_merge_extra_filerefs",
"(",
"kwarg... | Function to run a state with the given chunk via salt-ssh | [
"Function",
"to",
"run",
"a",
"state",
"with",
"the",
"given",
"chunk",
"via",
"salt",
"-",
"ssh"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L39-L89 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _set_retcode | def _set_retcode(ret, highstate=None):
'''
Set the return code based on the data back from the state system
'''
# Set default retcode to 0
__context__['retcode'] = 0
if isinstance(ret, list):
__context__['retcode'] = 1
return
if not salt.utils.state.check_result(ret, highstate=highstate):
__context__['retcode'] = 2 | python | def _set_retcode(ret, highstate=None):
'''
Set the return code based on the data back from the state system
'''
# Set default retcode to 0
__context__['retcode'] = 0
if isinstance(ret, list):
__context__['retcode'] = 1
return
if not salt.utils.state.check_result(ret, highstate=highstate):
__context__['retcode'] = 2 | [
"def",
"_set_retcode",
"(",
"ret",
",",
"highstate",
"=",
"None",
")",
":",
"# Set default retcode to 0",
"__context__",
"[",
"'retcode'",
"]",
"=",
"0",
"if",
"isinstance",
"(",
"ret",
",",
"list",
")",
":",
"__context__",
"[",
"'retcode'",
"]",
"=",
"1",... | Set the return code based on the data back from the state system | [
"Set",
"the",
"return",
"code",
"based",
"on",
"the",
"data",
"back",
"from",
"the",
"state",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L92-L105 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _check_pillar | def _check_pillar(kwargs, pillar=None):
'''
Check the pillar for errors, refuse to run the state if there are errors
in the pillar and return the pillar errors
'''
if kwargs.get('force'):
return True
pillar_dict = pillar if pillar is not None else __pillar__
if '_errors' in pillar_dict:
return False
return True | python | def _check_pillar(kwargs, pillar=None):
'''
Check the pillar for errors, refuse to run the state if there are errors
in the pillar and return the pillar errors
'''
if kwargs.get('force'):
return True
pillar_dict = pillar if pillar is not None else __pillar__
if '_errors' in pillar_dict:
return False
return True | [
"def",
"_check_pillar",
"(",
"kwargs",
",",
"pillar",
"=",
"None",
")",
":",
"if",
"kwargs",
".",
"get",
"(",
"'force'",
")",
":",
"return",
"True",
"pillar_dict",
"=",
"pillar",
"if",
"pillar",
"is",
"not",
"None",
"else",
"__pillar__",
"if",
"'_errors'... | Check the pillar for errors, refuse to run the state if there are errors
in the pillar and return the pillar errors | [
"Check",
"the",
"pillar",
"for",
"errors",
"refuse",
"to",
"run",
"the",
"state",
"if",
"there",
"are",
"errors",
"in",
"the",
"pillar",
"and",
"return",
"the",
"pillar",
"errors"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L108-L118 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _wait | def _wait(jid):
'''
Wait for all previously started state jobs to finish running
'''
if jid is None:
jid = salt.utils.jid.gen_jid(__opts__)
states = _prior_running_states(jid)
while states:
time.sleep(1)
states = _prior_running_states(jid) | python | def _wait(jid):
'''
Wait for all previously started state jobs to finish running
'''
if jid is None:
jid = salt.utils.jid.gen_jid(__opts__)
states = _prior_running_states(jid)
while states:
time.sleep(1)
states = _prior_running_states(jid) | [
"def",
"_wait",
"(",
"jid",
")",
":",
"if",
"jid",
"is",
"None",
":",
"jid",
"=",
"salt",
".",
"utils",
".",
"jid",
".",
"gen_jid",
"(",
"__opts__",
")",
"states",
"=",
"_prior_running_states",
"(",
"jid",
")",
"while",
"states",
":",
"time",
".",
... | Wait for all previously started state jobs to finish running | [
"Wait",
"for",
"all",
"previously",
"started",
"state",
"jobs",
"to",
"finish",
"running"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L121-L130 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _merge_extra_filerefs | def _merge_extra_filerefs(*args):
'''
Takes a list of filerefs and returns a merged list
'''
ret = []
for arg in args:
if isinstance(arg, six.string_types):
if arg:
ret.extend(arg.split(','))
elif isinstance(arg, list):
if arg:
ret.extend(arg)
return ','.join(ret) | python | def _merge_extra_filerefs(*args):
'''
Takes a list of filerefs and returns a merged list
'''
ret = []
for arg in args:
if isinstance(arg, six.string_types):
if arg:
ret.extend(arg.split(','))
elif isinstance(arg, list):
if arg:
ret.extend(arg)
return ','.join(ret) | [
"def",
"_merge_extra_filerefs",
"(",
"*",
"args",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"six",
".",
"string_types",
")",
":",
"if",
"arg",
":",
"ret",
".",
"extend",
"(",
"arg",
".",
... | Takes a list of filerefs and returns a merged list | [
"Takes",
"a",
"list",
"of",
"filerefs",
"and",
"returns",
"a",
"merged",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L133-L145 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _cleanup_slsmod_high_data | def _cleanup_slsmod_high_data(high_data):
'''
Set "slsmod" keys to None to make
high_data JSON serializable
'''
for i in six.itervalues(high_data):
if 'stateconf' in i:
stateconf_data = i['stateconf'][1]
if 'slsmod' in stateconf_data:
stateconf_data['slsmod'] = None | python | def _cleanup_slsmod_high_data(high_data):
'''
Set "slsmod" keys to None to make
high_data JSON serializable
'''
for i in six.itervalues(high_data):
if 'stateconf' in i:
stateconf_data = i['stateconf'][1]
if 'slsmod' in stateconf_data:
stateconf_data['slsmod'] = None | [
"def",
"_cleanup_slsmod_high_data",
"(",
"high_data",
")",
":",
"for",
"i",
"in",
"six",
".",
"itervalues",
"(",
"high_data",
")",
":",
"if",
"'stateconf'",
"in",
"i",
":",
"stateconf_data",
"=",
"i",
"[",
"'stateconf'",
"]",
"[",
"1",
"]",
"if",
"'slsmo... | Set "slsmod" keys to None to make
high_data JSON serializable | [
"Set",
"slsmod",
"keys",
"to",
"None",
"to",
"make",
"high_data",
"JSON",
"serializable"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L158-L167 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _parse_mods | def _parse_mods(mods):
'''
Parse modules.
'''
if isinstance(mods, six.string_types):
mods = [item.strip() for item in mods.split(',') if item.strip()]
return mods | python | def _parse_mods(mods):
'''
Parse modules.
'''
if isinstance(mods, six.string_types):
mods = [item.strip() for item in mods.split(',') if item.strip()]
return mods | [
"def",
"_parse_mods",
"(",
"mods",
")",
":",
"if",
"isinstance",
"(",
"mods",
",",
"six",
".",
"string_types",
")",
":",
"mods",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"mods",
".",
"split",
"(",
"','",
")",
"if",
"item",
"... | Parse modules. | [
"Parse",
"modules",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L170-L177 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | sls | def sls(mods, saltenv='base', test=None, exclude=None, **kwargs):
'''
Create the seed file for a state.sls run
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
__pillar__.update(kwargs.get('pillar', {}))
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
mods = _parse_mods(mods)
high_data, errors = st_.render_highstate({saltenv: mods})
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high_data:
high_data['__exclude__'].extend(exclude)
else:
high_data['__exclude__'] = exclude
high_data, ext_errors = st_.state.reconcile_extend(high_data)
errors += ext_errors
errors += st_.state.verify_high(high_data)
if errors:
return errors
high_data, req_in_errors = st_.state.requisite_in(high_data)
errors += req_in_errors
high_data = st_.state.apply_exclude(high_data)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = st_.state.compile_high_data(high_data)
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
opts.get('extra_filerefs', '')
)
)
roster = salt.roster.Roster(opts, opts.get('roster', 'flat'))
roster_grains = roster.opts['grains']
# Create the tar containing the state pkg and relevant files.
_cleanup_slsmod_low_data(chunks)
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'],
roster_grains)
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, opts['hash_type'])
cmd = 'state.pkg {0}/salt_state.tgz test={1} pkg_sum={2} hash_type={3}'.format(
opts['thin_dir'],
test,
trans_tar_sum,
opts['hash_type'])
single = salt.client.ssh.Single(
opts,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(opts['thin_dir']))
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.json.loads(stdout)
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(six.text_type(e))
# If for some reason the json load fails, return the stdout
return stdout | python | def sls(mods, saltenv='base', test=None, exclude=None, **kwargs):
'''
Create the seed file for a state.sls run
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
__pillar__.update(kwargs.get('pillar', {}))
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
mods = _parse_mods(mods)
high_data, errors = st_.render_highstate({saltenv: mods})
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high_data:
high_data['__exclude__'].extend(exclude)
else:
high_data['__exclude__'] = exclude
high_data, ext_errors = st_.state.reconcile_extend(high_data)
errors += ext_errors
errors += st_.state.verify_high(high_data)
if errors:
return errors
high_data, req_in_errors = st_.state.requisite_in(high_data)
errors += req_in_errors
high_data = st_.state.apply_exclude(high_data)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = st_.state.compile_high_data(high_data)
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
opts.get('extra_filerefs', '')
)
)
roster = salt.roster.Roster(opts, opts.get('roster', 'flat'))
roster_grains = roster.opts['grains']
# Create the tar containing the state pkg and relevant files.
_cleanup_slsmod_low_data(chunks)
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'],
roster_grains)
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, opts['hash_type'])
cmd = 'state.pkg {0}/salt_state.tgz test={1} pkg_sum={2} hash_type={3}'.format(
opts['thin_dir'],
test,
trans_tar_sum,
opts['hash_type'])
single = salt.client.ssh.Single(
opts,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(opts['thin_dir']))
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.json.loads(stdout)
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(six.text_type(e))
# If for some reason the json load fails, return the stdout
return stdout | [
"def",
"sls",
"(",
"mods",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
",",
"exclude",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"st_kwargs",
"=",
"__salt__",
".",
"kwargs",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"__p... | Create the seed file for a state.sls run | [
"Create",
"the",
"seed",
"file",
"for",
"a",
"state",
".",
"sls",
"run"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L180-L267 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | running | def running(concurrent=False):
'''
Return a list of strings that contain state return data if a state function
is already running. This function is used to prevent multiple state calls
from being run at the same time.
CLI Example:
.. code-block:: bash
salt '*' state.running
'''
ret = []
if concurrent:
return ret
active = __salt__['saltutil.is_running']('state.*')
for data in active:
err = (
'The function "{0}" is running as PID {1} and was started at '
'{2} with jid {3}'
).format(
data['fun'],
data['pid'],
salt.utils.jid.jid_to_time(data['jid']),
data['jid'],
)
ret.append(err)
return ret | python | def running(concurrent=False):
'''
Return a list of strings that contain state return data if a state function
is already running. This function is used to prevent multiple state calls
from being run at the same time.
CLI Example:
.. code-block:: bash
salt '*' state.running
'''
ret = []
if concurrent:
return ret
active = __salt__['saltutil.is_running']('state.*')
for data in active:
err = (
'The function "{0}" is running as PID {1} and was started at '
'{2} with jid {3}'
).format(
data['fun'],
data['pid'],
salt.utils.jid.jid_to_time(data['jid']),
data['jid'],
)
ret.append(err)
return ret | [
"def",
"running",
"(",
"concurrent",
"=",
"False",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"concurrent",
":",
"return",
"ret",
"active",
"=",
"__salt__",
"[",
"'saltutil.is_running'",
"]",
"(",
"'state.*'",
")",
"for",
"data",
"in",
"active",
":",
"err",
... | Return a list of strings that contain state return data if a state function
is already running. This function is used to prevent multiple state calls
from being run at the same time.
CLI Example:
.. code-block:: bash
salt '*' state.running | [
"Return",
"a",
"list",
"of",
"strings",
"that",
"contain",
"state",
"return",
"data",
"if",
"a",
"state",
"function",
"is",
"already",
"running",
".",
"This",
"function",
"is",
"used",
"to",
"prevent",
"multiple",
"state",
"calls",
"from",
"being",
"run",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L270-L297 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _prior_running_states | def _prior_running_states(jid):
'''
Return a list of dicts of prior calls to state functions. This function is
used to queue state calls so only one is run at a time.
'''
ret = []
active = __salt__['saltutil.is_running']('state.*')
for data in active:
try:
data_jid = int(data['jid'])
except ValueError:
continue
if data_jid < int(jid):
ret.append(data)
return ret | python | def _prior_running_states(jid):
'''
Return a list of dicts of prior calls to state functions. This function is
used to queue state calls so only one is run at a time.
'''
ret = []
active = __salt__['saltutil.is_running']('state.*')
for data in active:
try:
data_jid = int(data['jid'])
except ValueError:
continue
if data_jid < int(jid):
ret.append(data)
return ret | [
"def",
"_prior_running_states",
"(",
"jid",
")",
":",
"ret",
"=",
"[",
"]",
"active",
"=",
"__salt__",
"[",
"'saltutil.is_running'",
"]",
"(",
"'state.*'",
")",
"for",
"data",
"in",
"active",
":",
"try",
":",
"data_jid",
"=",
"int",
"(",
"data",
"[",
"... | Return a list of dicts of prior calls to state functions. This function is
used to queue state calls so only one is run at a time. | [
"Return",
"a",
"list",
"of",
"dicts",
"of",
"prior",
"calls",
"to",
"state",
"functions",
".",
"This",
"function",
"is",
"used",
"to",
"queue",
"state",
"calls",
"so",
"only",
"one",
"is",
"run",
"at",
"a",
"time",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L300-L315 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | _check_queue | def _check_queue(queue, kwargs):
'''
Utility function to queue the state run if requested
and to check for conflicts in currently running states
'''
if queue:
_wait(kwargs.get('__pub_jid'))
else:
conflict = running(concurrent=kwargs.get('concurrent', False))
if conflict:
__context__['retcode'] = 1
return conflict | python | def _check_queue(queue, kwargs):
'''
Utility function to queue the state run if requested
and to check for conflicts in currently running states
'''
if queue:
_wait(kwargs.get('__pub_jid'))
else:
conflict = running(concurrent=kwargs.get('concurrent', False))
if conflict:
__context__['retcode'] = 1
return conflict | [
"def",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
":",
"if",
"queue",
":",
"_wait",
"(",
"kwargs",
".",
"get",
"(",
"'__pub_jid'",
")",
")",
"else",
":",
"conflict",
"=",
"running",
"(",
"concurrent",
"=",
"kwargs",
".",
"get",
"(",
"'concurrent... | Utility function to queue the state run if requested
and to check for conflicts in currently running states | [
"Utility",
"function",
"to",
"queue",
"the",
"state",
"run",
"if",
"requested",
"and",
"to",
"check",
"for",
"conflicts",
"in",
"currently",
"running",
"states"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L318-L329 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | low | def low(data, **kwargs):
'''
Execute a single low data call
This function is mostly intended for testing the state system
CLI Example:
.. code-block:: bash
salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}'
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
chunks = [data]
st_ = salt.client.ssh.state.SSHHighState(
__opts__,
__pillar__,
__salt__,
__context__['fileclient'])
for chunk in chunks:
chunk['__id__'] = chunk['name'] if not chunk.get('__id__') else chunk['__id__']
err = st_.state.verify_data(data)
if err:
return err
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
__opts__.get('extra_filerefs', '')
)
)
roster = salt.roster.Roster(__opts__, __opts__.get('roster', 'flat'))
roster_grains = roster.opts['grains']
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'],
roster_grains)
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, __opts__['hash_type'])
cmd = 'state.pkg {0}/salt_state.tgz pkg_sum={1} hash_type={2}'.format(
__opts__['thin_dir'],
trans_tar_sum,
__opts__['hash_type'])
single = salt.client.ssh.Single(
__opts__,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(__opts__['thin_dir']))
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.json.loads(stdout)
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(six.text_type(e))
# If for some reason the json load fails, return the stdout
return stdout | python | def low(data, **kwargs):
'''
Execute a single low data call
This function is mostly intended for testing the state system
CLI Example:
.. code-block:: bash
salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}'
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
chunks = [data]
st_ = salt.client.ssh.state.SSHHighState(
__opts__,
__pillar__,
__salt__,
__context__['fileclient'])
for chunk in chunks:
chunk['__id__'] = chunk['name'] if not chunk.get('__id__') else chunk['__id__']
err = st_.state.verify_data(data)
if err:
return err
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
__opts__.get('extra_filerefs', '')
)
)
roster = salt.roster.Roster(__opts__, __opts__.get('roster', 'flat'))
roster_grains = roster.opts['grains']
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'],
roster_grains)
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, __opts__['hash_type'])
cmd = 'state.pkg {0}/salt_state.tgz pkg_sum={1} hash_type={2}'.format(
__opts__['thin_dir'],
trans_tar_sum,
__opts__['hash_type'])
single = salt.client.ssh.Single(
__opts__,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(__opts__['thin_dir']))
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.json.loads(stdout)
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(six.text_type(e))
# If for some reason the json load fails, return the stdout
return stdout | [
"def",
"low",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"st_kwargs",
"=",
"__salt__",
".",
"kwargs",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"chunks",
"=",
"[",
"data",
"]",
"st_",
"=",
"salt",
".",
"client",
".",
"ssh",
".",
"st... | Execute a single low data call
This function is mostly intended for testing the state system
CLI Example:
.. code-block:: bash
salt '*' state.low '{"state": "pkg", "fun": "installed", "name": "vi"}' | [
"Execute",
"a",
"single",
"low",
"data",
"call",
"This",
"function",
"is",
"mostly",
"intended",
"for",
"testing",
"the",
"state",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L338-L410 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | request | def request(mods=None,
**kwargs):
'''
.. versionadded:: 2017.7.3
Request that the local admin execute a state run via
`salt-call state.run_request`
All arguments match state.apply
CLI Example:
.. code-block:: bash
salt '*' state.request
salt '*' state.request test
salt '*' state.request test,pkgs
'''
kwargs['test'] = True
ret = apply_(mods, **kwargs)
notify_path = os.path.join(__opts__['cachedir'], 'req_state.p')
serial = salt.payload.Serial(__opts__)
req = check_request()
req.update({kwargs.get('name', 'default'): {
'test_run': ret,
'mods': mods,
'kwargs': kwargs
}
})
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
__salt__['cmd.run']('attrib -R "{0}"'.format(notify_path))
with salt.utils.files.fopen(notify_path, 'w+b') as fp_:
serial.dump(req, fp_)
except (IOError, OSError):
log.error(
'Unable to write state request file %s. Check permission.',
notify_path
)
return ret | python | def request(mods=None,
**kwargs):
'''
.. versionadded:: 2017.7.3
Request that the local admin execute a state run via
`salt-call state.run_request`
All arguments match state.apply
CLI Example:
.. code-block:: bash
salt '*' state.request
salt '*' state.request test
salt '*' state.request test,pkgs
'''
kwargs['test'] = True
ret = apply_(mods, **kwargs)
notify_path = os.path.join(__opts__['cachedir'], 'req_state.p')
serial = salt.payload.Serial(__opts__)
req = check_request()
req.update({kwargs.get('name', 'default'): {
'test_run': ret,
'mods': mods,
'kwargs': kwargs
}
})
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
__salt__['cmd.run']('attrib -R "{0}"'.format(notify_path))
with salt.utils.files.fopen(notify_path, 'w+b') as fp_:
serial.dump(req, fp_)
except (IOError, OSError):
log.error(
'Unable to write state request file %s. Check permission.',
notify_path
)
return ret | [
"def",
"request",
"(",
"mods",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'test'",
"]",
"=",
"True",
"ret",
"=",
"apply_",
"(",
"mods",
",",
"*",
"*",
"kwargs",
")",
"notify_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | .. versionadded:: 2017.7.3
Request that the local admin execute a state run via
`salt-call state.run_request`
All arguments match state.apply
CLI Example:
.. code-block:: bash
salt '*' state.request
salt '*' state.request test
salt '*' state.request test,pkgs | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"3"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L525-L565 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | clear_request | def clear_request(name=None):
'''
.. versionadded:: 2017.7.3
Clear out the state execution request without executing it
CLI Example:
.. code-block:: bash
salt '*' state.clear_request
'''
notify_path = os.path.join(__opts__['cachedir'], 'req_state.p')
serial = salt.payload.Serial(__opts__)
if not os.path.isfile(notify_path):
return True
if not name:
try:
os.remove(notify_path)
except (IOError, OSError):
pass
else:
req = check_request()
if name in req:
req.pop(name)
else:
return False
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
__salt__['cmd.run']('attrib -R "{0}"'.format(notify_path))
with salt.utils.files.fopen(notify_path, 'w+b') as fp_:
serial.dump(req, fp_)
except (IOError, OSError):
log.error(
'Unable to write state request file %s. Check permission.',
notify_path
)
return True | python | def clear_request(name=None):
'''
.. versionadded:: 2017.7.3
Clear out the state execution request without executing it
CLI Example:
.. code-block:: bash
salt '*' state.clear_request
'''
notify_path = os.path.join(__opts__['cachedir'], 'req_state.p')
serial = salt.payload.Serial(__opts__)
if not os.path.isfile(notify_path):
return True
if not name:
try:
os.remove(notify_path)
except (IOError, OSError):
pass
else:
req = check_request()
if name in req:
req.pop(name)
else:
return False
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
__salt__['cmd.run']('attrib -R "{0}"'.format(notify_path))
with salt.utils.files.fopen(notify_path, 'w+b') as fp_:
serial.dump(req, fp_)
except (IOError, OSError):
log.error(
'Unable to write state request file %s. Check permission.',
notify_path
)
return True | [
"def",
"clear_request",
"(",
"name",
"=",
"None",
")",
":",
"notify_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'req_state.p'",
")",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"__opts__",
"... | .. versionadded:: 2017.7.3
Clear out the state execution request without executing it
CLI Example:
.. code-block:: bash
salt '*' state.clear_request | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"3"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L593-L632 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | run_request | def run_request(name='default', **kwargs):
'''
.. versionadded:: 2017.7.3
Execute the pending state request
CLI Example:
.. code-block:: bash
salt '*' state.run_request
'''
req = check_request()
if name not in req:
return {}
n_req = req[name]
if 'mods' not in n_req or 'kwargs' not in n_req:
return {}
req[name]['kwargs'].update(kwargs)
if 'test' in n_req['kwargs']:
n_req['kwargs'].pop('test')
if req:
ret = apply_(n_req['mods'], **n_req['kwargs'])
try:
os.remove(os.path.join(__opts__['cachedir'], 'req_state.p'))
except (IOError, OSError):
pass
return ret
return {} | python | def run_request(name='default', **kwargs):
'''
.. versionadded:: 2017.7.3
Execute the pending state request
CLI Example:
.. code-block:: bash
salt '*' state.run_request
'''
req = check_request()
if name not in req:
return {}
n_req = req[name]
if 'mods' not in n_req or 'kwargs' not in n_req:
return {}
req[name]['kwargs'].update(kwargs)
if 'test' in n_req['kwargs']:
n_req['kwargs'].pop('test')
if req:
ret = apply_(n_req['mods'], **n_req['kwargs'])
try:
os.remove(os.path.join(__opts__['cachedir'], 'req_state.p'))
except (IOError, OSError):
pass
return ret
return {} | [
"def",
"run_request",
"(",
"name",
"=",
"'default'",
",",
"*",
"*",
"kwargs",
")",
":",
"req",
"=",
"check_request",
"(",
")",
"if",
"name",
"not",
"in",
"req",
":",
"return",
"{",
"}",
"n_req",
"=",
"req",
"[",
"name",
"]",
"if",
"'mods'",
"not",
... | .. versionadded:: 2017.7.3
Execute the pending state request
CLI Example:
.. code-block:: bash
salt '*' state.run_request | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"3"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L635-L663 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | show_highstate | def show_highstate(**kwargs):
'''
Retrieve the highstate data from the salt master and display it
CLI Example:
.. code-block:: bash
salt '*' state.show_highstate
'''
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
chunks = st_.compile_highstate()
_cleanup_slsmod_high_data(chunks)
return chunks | python | def show_highstate(**kwargs):
'''
Retrieve the highstate data from the salt master and display it
CLI Example:
.. code-block:: bash
salt '*' state.show_highstate
'''
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
chunks = st_.compile_highstate()
_cleanup_slsmod_high_data(chunks)
return chunks | [
"def",
"show_highstate",
"(",
"*",
"*",
"kwargs",
")",
":",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"opts",
"=",
"salt",
".",
"utils",
".",
"state",
".",
"get_sls_opts",
"(",
"__opts__",
",",
"*",
"*",
"kwargs",
")",
"st_",
"=",
"salt",
... | Retrieve the highstate data from the salt master and display it
CLI Example:
.. code-block:: bash
salt '*' state.show_highstate | [
"Retrieve",
"the",
"highstate",
"data",
"from",
"the",
"salt",
"master",
"and",
"display",
"it"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L831-L851 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | show_lowstate | def show_lowstate(**kwargs):
'''
List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate
'''
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
chunks = st_.compile_low_chunks()
_cleanup_slsmod_low_data(chunks)
return chunks | python | def show_lowstate(**kwargs):
'''
List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate
'''
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
chunks = st_.compile_low_chunks()
_cleanup_slsmod_low_data(chunks)
return chunks | [
"def",
"show_lowstate",
"(",
"*",
"*",
"kwargs",
")",
":",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"opts",
"=",
"salt",
".",
"utils",
".",
"state",
".",
"get_sls_opts",
"(",
"__opts__",
",",
"*",
"*",
"kwargs",
")",
"st_",
"=",
"salt",
"... | List out the low data that will be applied to this minion
CLI Example:
.. code-block:: bash
salt '*' state.show_lowstate | [
"List",
"out",
"the",
"low",
"data",
"that",
"will",
"be",
"applied",
"to",
"this",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L854-L874 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | sls_id | def sls_id(id_, mods, test=None, queue=False, **kwargs):
'''
Call a single ID from the named module(s) and handle all requisites
The state ID comes *before* the module ID(s) on the command line.
id
ID to call
mods
Comma-delimited list of modules to search for given id and its requisites
.. versionadded:: 2017.7.3
saltenv : base
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
CLI Example:
.. code-block:: bash
salt '*' state.sls_id my_state my_module
salt '*' state.sls_id my_state my_module,a_common_module
'''
st_kwargs = __salt__.kwargs
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is running a specific ID within a specific SLS file, fall back
# to the 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
st_ = salt.client.ssh.state.SSHHighState(
__opts__,
__pillar__,
__salt__,
__context__['fileclient'])
if not _check_pillar(kwargs, st_.opts['pillar']):
__context__['retcode'] = 5
err = ['Pillar failed to render with the following messages:']
err += __pillar__['_errors']
return err
split_mods = _parse_mods(mods)
st_.push_active()
high_, errors = st_.render_highstate({opts['saltenv']: split_mods})
errors += st_.state.verify_high(high_)
# Apply requisites to high data
high_, req_in_errors = st_.state.requisite_in(high_)
if req_in_errors:
# This if statement should not be necessary if there were no errors,
# but it is required to get the unit tests to pass.
errors.extend(req_in_errors)
if errors:
__context__['retcode'] = 1
return errors
chunks = st_.state.compile_high_data(high_)
chunk = [x for x in chunks if x.get('__id__', '') == id_]
if not chunk:
raise SaltInvocationError(
'No matches for ID \'{0}\' found in SLS \'{1}\' within saltenv '
'\'{2}\''.format(id_, mods, opts['saltenv'])
)
ret = _ssh_state(chunk,
st_kwargs,
kwargs,
test=test)
_set_retcode(ret, highstate=highstate)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
return ret | python | def sls_id(id_, mods, test=None, queue=False, **kwargs):
'''
Call a single ID from the named module(s) and handle all requisites
The state ID comes *before* the module ID(s) on the command line.
id
ID to call
mods
Comma-delimited list of modules to search for given id and its requisites
.. versionadded:: 2017.7.3
saltenv : base
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
CLI Example:
.. code-block:: bash
salt '*' state.sls_id my_state my_module
salt '*' state.sls_id my_state my_module,a_common_module
'''
st_kwargs = __salt__.kwargs
conflict = _check_queue(queue, kwargs)
if conflict is not None:
return conflict
orig_test = __opts__.get('test', None)
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
opts['test'] = _get_test_value(test, **kwargs)
# Since this is running a specific ID within a specific SLS file, fall back
# to the 'base' saltenv if none is configured and none was passed.
if opts['saltenv'] is None:
opts['saltenv'] = 'base'
st_ = salt.client.ssh.state.SSHHighState(
__opts__,
__pillar__,
__salt__,
__context__['fileclient'])
if not _check_pillar(kwargs, st_.opts['pillar']):
__context__['retcode'] = 5
err = ['Pillar failed to render with the following messages:']
err += __pillar__['_errors']
return err
split_mods = _parse_mods(mods)
st_.push_active()
high_, errors = st_.render_highstate({opts['saltenv']: split_mods})
errors += st_.state.verify_high(high_)
# Apply requisites to high data
high_, req_in_errors = st_.state.requisite_in(high_)
if req_in_errors:
# This if statement should not be necessary if there were no errors,
# but it is required to get the unit tests to pass.
errors.extend(req_in_errors)
if errors:
__context__['retcode'] = 1
return errors
chunks = st_.state.compile_high_data(high_)
chunk = [x for x in chunks if x.get('__id__', '') == id_]
if not chunk:
raise SaltInvocationError(
'No matches for ID \'{0}\' found in SLS \'{1}\' within saltenv '
'\'{2}\''.format(id_, mods, opts['saltenv'])
)
ret = _ssh_state(chunk,
st_kwargs,
kwargs,
test=test)
_set_retcode(ret, highstate=highstate)
# Work around Windows multiprocessing bug, set __opts__['test'] back to
# value from before this function was run.
__opts__['test'] = orig_test
return ret | [
"def",
"sls_id",
"(",
"id_",
",",
"mods",
",",
"test",
"=",
"None",
",",
"queue",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"st_kwargs",
"=",
"__salt__",
".",
"kwargs",
"conflict",
"=",
"_check_queue",
"(",
"queue",
",",
"kwargs",
")",
"if",
... | Call a single ID from the named module(s) and handle all requisites
The state ID comes *before* the module ID(s) on the command line.
id
ID to call
mods
Comma-delimited list of modules to search for given id and its requisites
.. versionadded:: 2017.7.3
saltenv : base
Specify a salt fileserver environment to be used when applying states
pillarenv
Specify a Pillar environment to be used when applying states. This
can also be set in the minion config file using the
:conf_minion:`pillarenv` option. When neither the
:conf_minion:`pillarenv` minion config option nor this CLI argument is
used, all Pillar environments will be merged together.
CLI Example:
.. code-block:: bash
salt '*' state.sls_id my_state my_module
salt '*' state.sls_id my_state my_module,a_common_module | [
"Call",
"a",
"single",
"ID",
"from",
"the",
"named",
"module",
"(",
"s",
")",
"and",
"handle",
"all",
"requisites"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L877-L964 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | show_sls | def show_sls(mods, saltenv='base', test=None, **kwargs):
'''
Display the state data from a specific sls or list of sls files on the
master
CLI Example:
.. code-block:: bash
salt '*' state.show_sls core,edit.vim dev
'''
__pillar__.update(kwargs.get('pillar', {}))
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
if salt.utils.args.test_mode(test=test, **kwargs):
opts['test'] = True
else:
opts['test'] = __opts__.get('test', None)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
mods = _parse_mods(mods)
high_data, errors = st_.render_highstate({saltenv: mods})
high_data, ext_errors = st_.state.reconcile_extend(high_data)
errors += ext_errors
errors += st_.state.verify_high(high_data)
if errors:
return errors
high_data, req_in_errors = st_.state.requisite_in(high_data)
errors += req_in_errors
high_data = st_.state.apply_exclude(high_data)
# Verify that the high data is structurally sound
if errors:
return errors
_cleanup_slsmod_high_data(high_data)
return high_data | python | def show_sls(mods, saltenv='base', test=None, **kwargs):
'''
Display the state data from a specific sls or list of sls files on the
master
CLI Example:
.. code-block:: bash
salt '*' state.show_sls core,edit.vim dev
'''
__pillar__.update(kwargs.get('pillar', {}))
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
if salt.utils.args.test_mode(test=test, **kwargs):
opts['test'] = True
else:
opts['test'] = __opts__.get('test', None)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
st_.push_active()
mods = _parse_mods(mods)
high_data, errors = st_.render_highstate({saltenv: mods})
high_data, ext_errors = st_.state.reconcile_extend(high_data)
errors += ext_errors
errors += st_.state.verify_high(high_data)
if errors:
return errors
high_data, req_in_errors = st_.state.requisite_in(high_data)
errors += req_in_errors
high_data = st_.state.apply_exclude(high_data)
# Verify that the high data is structurally sound
if errors:
return errors
_cleanup_slsmod_high_data(high_data)
return high_data | [
"def",
"show_sls",
"(",
"mods",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"__pillar__",
".",
"update",
"(",
"kwargs",
".",
"get",
"(",
"'pillar'",
",",
"{",
"}",
")",
")",
"__opts__",
"[",
"'grains'... | Display the state data from a specific sls or list of sls files on the
master
CLI Example:
.. code-block:: bash
salt '*' state.show_sls core,edit.vim dev | [
"Display",
"the",
"state",
"data",
"from",
"a",
"specific",
"sls",
"or",
"list",
"of",
"sls",
"files",
"on",
"the",
"master"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L967-L1005 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | show_top | def show_top(**kwargs):
'''
Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top
'''
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
top_data = st_.get_top()
errors = []
errors += st_.verify_tops(top_data)
if errors:
return errors
matches = st_.top_matches(top_data)
return matches | python | def show_top(**kwargs):
'''
Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top
'''
__opts__['grains'] = __grains__
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.client.ssh.state.SSHHighState(
opts,
__pillar__,
__salt__,
__context__['fileclient'])
top_data = st_.get_top()
errors = []
errors += st_.verify_tops(top_data)
if errors:
return errors
matches = st_.top_matches(top_data)
return matches | [
"def",
"show_top",
"(",
"*",
"*",
"kwargs",
")",
":",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"opts",
"=",
"salt",
".",
"utils",
".",
"state",
".",
"get_sls_opts",
"(",
"__opts__",
",",
"*",
"*",
"kwargs",
")",
"st_",
"=",
"salt",
".",
... | Return the top data that the minion will use for a highstate
CLI Example:
.. code-block:: bash
salt '*' state.show_top | [
"Return",
"the",
"top",
"data",
"that",
"the",
"minion",
"will",
"use",
"for",
"a",
"highstate"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L1053-L1076 | train |
saltstack/salt | salt/client/ssh/wrapper/state.py | single | def single(fun, name, test=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of single entry key-value maps, as you
would in a YAML salt file. Alternatively, JSON format of keyword values
is also supported.
CLI Example:
.. code-block:: bash
salt '*' state.single pkg.installed name=vim
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
# state.fun -> [state, fun]
comps = fun.split('.')
if len(comps) < 2:
__context__['retcode'] = 1
return 'Invalid function passed'
# Create the low chunk, using kwargs as a base
kwargs.update({'state': comps[0],
'fun': comps[1],
'__id__': name,
'name': name})
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
# Set test mode
if salt.utils.args.test_mode(test=test, **kwargs):
opts['test'] = True
else:
opts['test'] = __opts__.get('test', None)
# Get the override pillar data
__pillar__.update(kwargs.get('pillar', {}))
# Create the State environment
st_ = salt.client.ssh.state.SSHState(opts, __pillar__)
# Verify the low chunk
err = st_.verify_data(kwargs)
if err:
__context__['retcode'] = 1
return err
# Must be a list of low-chunks
chunks = [kwargs]
# Retrieve file refs for the state run, so we can copy relevant files down
# to the minion before executing the state
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
opts.get('extra_filerefs', '')
)
)
roster = salt.roster.Roster(opts, opts.get('roster', 'flat'))
roster_grains = roster.opts['grains']
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'],
roster_grains)
# Create a hash so we can verify the tar on the target system
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, opts['hash_type'])
# We use state.pkg to execute the "state package"
cmd = 'state.pkg {0}/salt_state.tgz test={1} pkg_sum={2} hash_type={3}'.format(
opts['thin_dir'],
test,
trans_tar_sum,
opts['hash_type'])
# Create a salt-ssh Single object to actually do the ssh work
single = salt.client.ssh.Single(
opts,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
# Copy the tar down
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(opts['thin_dir']))
# Run the state.pkg command on the target
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.json.loads(stdout)
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(six.text_type(e))
# If for some reason the json load fails, return the stdout
return stdout | python | def single(fun, name, test=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of single entry key-value maps, as you
would in a YAML salt file. Alternatively, JSON format of keyword values
is also supported.
CLI Example:
.. code-block:: bash
salt '*' state.single pkg.installed name=vim
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
# state.fun -> [state, fun]
comps = fun.split('.')
if len(comps) < 2:
__context__['retcode'] = 1
return 'Invalid function passed'
# Create the low chunk, using kwargs as a base
kwargs.update({'state': comps[0],
'fun': comps[1],
'__id__': name,
'name': name})
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
# Set test mode
if salt.utils.args.test_mode(test=test, **kwargs):
opts['test'] = True
else:
opts['test'] = __opts__.get('test', None)
# Get the override pillar data
__pillar__.update(kwargs.get('pillar', {}))
# Create the State environment
st_ = salt.client.ssh.state.SSHState(opts, __pillar__)
# Verify the low chunk
err = st_.verify_data(kwargs)
if err:
__context__['retcode'] = 1
return err
# Must be a list of low-chunks
chunks = [kwargs]
# Retrieve file refs for the state run, so we can copy relevant files down
# to the minion before executing the state
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
_merge_extra_filerefs(
kwargs.get('extra_filerefs', ''),
opts.get('extra_filerefs', '')
)
)
roster = salt.roster.Roster(opts, opts.get('roster', 'flat'))
roster_grains = roster.opts['grains']
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__context__['fileclient'],
chunks,
file_refs,
__pillar__,
st_kwargs['id_'],
roster_grains)
# Create a hash so we can verify the tar on the target system
trans_tar_sum = salt.utils.hashutils.get_hash(trans_tar, opts['hash_type'])
# We use state.pkg to execute the "state package"
cmd = 'state.pkg {0}/salt_state.tgz test={1} pkg_sum={2} hash_type={3}'.format(
opts['thin_dir'],
test,
trans_tar_sum,
opts['hash_type'])
# Create a salt-ssh Single object to actually do the ssh work
single = salt.client.ssh.Single(
opts,
cmd,
fsclient=__context__['fileclient'],
minion_opts=__salt__.minion_opts,
**st_kwargs)
# Copy the tar down
single.shell.send(
trans_tar,
'{0}/salt_state.tgz'.format(opts['thin_dir']))
# Run the state.pkg command on the target
stdout, stderr, _ = single.cmd_block()
# Clean up our tar
try:
os.remove(trans_tar)
except (OSError, IOError):
pass
# Read in the JSON data and return the data structure
try:
return salt.utils.json.loads(stdout)
except Exception as e:
log.error("JSON Render failed for: %s\n%s", stdout, stderr)
log.error(six.text_type(e))
# If for some reason the json load fails, return the stdout
return stdout | [
"def",
"single",
"(",
"fun",
",",
"name",
",",
"test",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"st_kwargs",
"=",
"__salt__",
".",
"kwargs",
"__opts__",
"[",
"'grains'",
"]",
"=",
"__grains__",
"# state.fun -> [state, fun]",
"comps",
"=",
"fun",
"... | .. versionadded:: 2015.5.0
Execute a single state function with the named kwargs, returns False if
insufficient data is sent to the command
By default, the values of the kwargs will be parsed as YAML. So, you can
specify lists values, or lists of single entry key-value maps, as you
would in a YAML salt file. Alternatively, JSON format of keyword values
is also supported.
CLI Example:
.. code-block:: bash
salt '*' state.single pkg.installed name=vim | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/state.py#L1079-L1198 | train |
saltstack/salt | salt/modules/datadog_api.py | _initialize_connection | def _initialize_connection(api_key, app_key):
'''
Initialize Datadog connection
'''
if api_key is None:
raise SaltInvocationError('api_key must be specified')
if app_key is None:
raise SaltInvocationError('app_key must be specified')
options = {
'api_key': api_key,
'app_key': app_key
}
datadog.initialize(**options) | python | def _initialize_connection(api_key, app_key):
'''
Initialize Datadog connection
'''
if api_key is None:
raise SaltInvocationError('api_key must be specified')
if app_key is None:
raise SaltInvocationError('app_key must be specified')
options = {
'api_key': api_key,
'app_key': app_key
}
datadog.initialize(**options) | [
"def",
"_initialize_connection",
"(",
"api_key",
",",
"app_key",
")",
":",
"if",
"api_key",
"is",
"None",
":",
"raise",
"SaltInvocationError",
"(",
"'api_key must be specified'",
")",
"if",
"app_key",
"is",
"None",
":",
"raise",
"SaltInvocationError",
"(",
"'app_k... | Initialize Datadog connection | [
"Initialize",
"Datadog",
"connection"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/datadog_api.py#L41-L53 | train |
saltstack/salt | salt/modules/datadog_api.py | schedule_downtime | def schedule_downtime(scope,
api_key=None,
app_key=None,
monitor_id=None,
start=None,
end=None,
message=None,
recurrence=None,
timezone=None,
test=False):
'''
Schedule downtime for a scope of monitors.
CLI Example:
.. code-block:: bash
salt-call datadog.schedule_downtime 'host:app2' \\
stop=$(date --date='30 minutes' +%s) \\
app_key='0123456789' \\
api_key='9876543210'
Optional arguments
:param monitor_id: The ID of the monitor
:param start: Start time in seconds since the epoch
:param end: End time in seconds since the epoch
:param message: A message to send in a notification for this downtime
:param recurrence: Repeat this downtime periodically
:param timezone: Specify the timezone
'''
ret = {'result': False,
'response': None,
'comment': ''}
if api_key is None:
raise SaltInvocationError('api_key must be specified')
if app_key is None:
raise SaltInvocationError('app_key must be specified')
if test is True:
ret['result'] = True
ret['comment'] = 'A schedule downtime API call would have been made.'
return ret
_initialize_connection(api_key, app_key)
# Schedule downtime
try:
response = datadog.api.Downtime.create(scope=scope,
monitor_id=monitor_id,
start=start,
end=end,
message=message,
recurrence=recurrence,
timezone=timezone)
except ValueError:
comment = ('Unexpected exception in Datadog Schedule Downtime API '
'call. Are your keys correct?')
ret['comment'] = comment
return ret
ret['response'] = response
if 'active' in response.keys():
ret['result'] = True
ret['comment'] = 'Successfully scheduled downtime'
return ret | python | def schedule_downtime(scope,
api_key=None,
app_key=None,
monitor_id=None,
start=None,
end=None,
message=None,
recurrence=None,
timezone=None,
test=False):
'''
Schedule downtime for a scope of monitors.
CLI Example:
.. code-block:: bash
salt-call datadog.schedule_downtime 'host:app2' \\
stop=$(date --date='30 minutes' +%s) \\
app_key='0123456789' \\
api_key='9876543210'
Optional arguments
:param monitor_id: The ID of the monitor
:param start: Start time in seconds since the epoch
:param end: End time in seconds since the epoch
:param message: A message to send in a notification for this downtime
:param recurrence: Repeat this downtime periodically
:param timezone: Specify the timezone
'''
ret = {'result': False,
'response': None,
'comment': ''}
if api_key is None:
raise SaltInvocationError('api_key must be specified')
if app_key is None:
raise SaltInvocationError('app_key must be specified')
if test is True:
ret['result'] = True
ret['comment'] = 'A schedule downtime API call would have been made.'
return ret
_initialize_connection(api_key, app_key)
# Schedule downtime
try:
response = datadog.api.Downtime.create(scope=scope,
monitor_id=monitor_id,
start=start,
end=end,
message=message,
recurrence=recurrence,
timezone=timezone)
except ValueError:
comment = ('Unexpected exception in Datadog Schedule Downtime API '
'call. Are your keys correct?')
ret['comment'] = comment
return ret
ret['response'] = response
if 'active' in response.keys():
ret['result'] = True
ret['comment'] = 'Successfully scheduled downtime'
return ret | [
"def",
"schedule_downtime",
"(",
"scope",
",",
"api_key",
"=",
"None",
",",
"app_key",
"=",
"None",
",",
"monitor_id",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"message",
"=",
"None",
",",
"recurrence",
"=",
"None",
",",
... | Schedule downtime for a scope of monitors.
CLI Example:
.. code-block:: bash
salt-call datadog.schedule_downtime 'host:app2' \\
stop=$(date --date='30 minutes' +%s) \\
app_key='0123456789' \\
api_key='9876543210'
Optional arguments
:param monitor_id: The ID of the monitor
:param start: Start time in seconds since the epoch
:param end: End time in seconds since the epoch
:param message: A message to send in a notification for this downtime
:param recurrence: Repeat this downtime periodically
:param timezone: Specify the timezone | [
"Schedule",
"downtime",
"for",
"a",
"scope",
"of",
"monitors",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/datadog_api.py#L56-L120 | train |
saltstack/salt | salt/modules/datadog_api.py | cancel_downtime | def cancel_downtime(api_key=None,
app_key=None,
scope=None,
id=None):
'''
Cancel a downtime by id or by scope.
CLI Example:
.. code-block:: bash
salt-call datadog.cancel_downtime scope='host:app01' \\
api_key='0123456789' \\
app_key='9876543210'`
Arguments - Either scope or id is required.
:param id: The downtime ID
:param scope: The downtime scope
'''
if api_key is None:
raise SaltInvocationError('api_key must be specified')
if app_key is None:
raise SaltInvocationError('app_key must be specified')
_initialize_connection(api_key, app_key)
ret = {'result': False,
'response': None,
'comment': ''}
if id:
response = datadog.api.Downtime.delete(id)
ret['response'] = response
if not response: # Then call has succeeded
ret['result'] = True
ret['comment'] = 'Successfully cancelled downtime'
return ret
elif scope:
params = {
'api_key': api_key,
'application_key': app_key,
'scope': scope
}
response = requests.post(
'https://app.datadoghq.com/api/v1/downtime/cancel/by_scope',
params=params
)
if response.status_code == 200:
ret['result'] = True
ret['response'] = response.json()
ret['comment'] = 'Successfully cancelled downtime'
else:
ret['response'] = response.text
ret['comment'] = 'Status Code: {}'.format(response.status_code)
return ret
else:
raise SaltInvocationError('One of id or scope must be specified')
return ret | python | def cancel_downtime(api_key=None,
app_key=None,
scope=None,
id=None):
'''
Cancel a downtime by id or by scope.
CLI Example:
.. code-block:: bash
salt-call datadog.cancel_downtime scope='host:app01' \\
api_key='0123456789' \\
app_key='9876543210'`
Arguments - Either scope or id is required.
:param id: The downtime ID
:param scope: The downtime scope
'''
if api_key is None:
raise SaltInvocationError('api_key must be specified')
if app_key is None:
raise SaltInvocationError('app_key must be specified')
_initialize_connection(api_key, app_key)
ret = {'result': False,
'response': None,
'comment': ''}
if id:
response = datadog.api.Downtime.delete(id)
ret['response'] = response
if not response: # Then call has succeeded
ret['result'] = True
ret['comment'] = 'Successfully cancelled downtime'
return ret
elif scope:
params = {
'api_key': api_key,
'application_key': app_key,
'scope': scope
}
response = requests.post(
'https://app.datadoghq.com/api/v1/downtime/cancel/by_scope',
params=params
)
if response.status_code == 200:
ret['result'] = True
ret['response'] = response.json()
ret['comment'] = 'Successfully cancelled downtime'
else:
ret['response'] = response.text
ret['comment'] = 'Status Code: {}'.format(response.status_code)
return ret
else:
raise SaltInvocationError('One of id or scope must be specified')
return ret | [
"def",
"cancel_downtime",
"(",
"api_key",
"=",
"None",
",",
"app_key",
"=",
"None",
",",
"scope",
"=",
"None",
",",
"id",
"=",
"None",
")",
":",
"if",
"api_key",
"is",
"None",
":",
"raise",
"SaltInvocationError",
"(",
"'api_key must be specified'",
")",
"i... | Cancel a downtime by id or by scope.
CLI Example:
.. code-block:: bash
salt-call datadog.cancel_downtime scope='host:app01' \\
api_key='0123456789' \\
app_key='9876543210'`
Arguments - Either scope or id is required.
:param id: The downtime ID
:param scope: The downtime scope | [
"Cancel",
"a",
"downtime",
"by",
"id",
"or",
"by",
"scope",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/datadog_api.py#L123-L180 | train |
saltstack/salt | salt/modules/datadog_api.py | post_event | def post_event(api_key=None,
app_key=None,
title=None,
text=None,
date_happened=None,
priority=None,
host=None,
tags=None,
alert_type=None,
aggregation_key=None,
source_type_name=None):
'''
Post an event to the Datadog stream.
CLI Example
.. code-block:: bash
salt-call datadog.post_event api_key='0123456789' \\
app_key='9876543210' \\
title='Salt Highstate' \\
text="Salt highstate was run on $(salt-call grains.get id)" \\
tags='["service:salt", "event:highstate"]'
Required arguments
:param title: The event title. Limited to 100 characters.
:param text: The body of the event. Limited to 4000 characters. The text
supports markdown.
Optional arguments
:param date_happened: POSIX timestamp of the event.
:param priority: The priority of the event ('normal' or 'low').
:param host: Host name to associate with the event.
:param tags: A list of tags to apply to the event.
:param alert_type: "error", "warning", "info" or "success".
:param aggregation_key: An arbitrary string to use for aggregation,
max length of 100 characters.
:param source_type_name: The type of event being posted.
'''
_initialize_connection(api_key, app_key)
if title is None:
raise SaltInvocationError('title must be specified')
if text is None:
raise SaltInvocationError('text must be specified')
if alert_type not in [None, 'error', 'warning', 'info', 'success']:
# Datadog only supports these alert types but the API doesn't return an
# error for an incorrect alert_type, so we can do it here for now.
# https://github.com/DataDog/datadogpy/issues/215
message = ('alert_type must be one of "error", "warning", "info", or '
'"success"')
raise SaltInvocationError(message)
ret = {'result': False,
'response': None,
'comment': ''}
try:
response = datadog.api.Event.create(title=title,
text=text,
date_happened=date_happened,
priority=priority,
host=host,
tags=tags,
alert_type=alert_type,
aggregation_key=aggregation_key,
source_type_name=source_type_name
)
except ValueError:
comment = ('Unexpected exception in Datadog Post Event API '
'call. Are your keys correct?')
ret['comment'] = comment
return ret
ret['response'] = response
if 'status' in response.keys():
ret['result'] = True
ret['comment'] = 'Successfully sent event'
else:
ret['comment'] = 'Error in posting event.'
return ret | python | def post_event(api_key=None,
app_key=None,
title=None,
text=None,
date_happened=None,
priority=None,
host=None,
tags=None,
alert_type=None,
aggregation_key=None,
source_type_name=None):
'''
Post an event to the Datadog stream.
CLI Example
.. code-block:: bash
salt-call datadog.post_event api_key='0123456789' \\
app_key='9876543210' \\
title='Salt Highstate' \\
text="Salt highstate was run on $(salt-call grains.get id)" \\
tags='["service:salt", "event:highstate"]'
Required arguments
:param title: The event title. Limited to 100 characters.
:param text: The body of the event. Limited to 4000 characters. The text
supports markdown.
Optional arguments
:param date_happened: POSIX timestamp of the event.
:param priority: The priority of the event ('normal' or 'low').
:param host: Host name to associate with the event.
:param tags: A list of tags to apply to the event.
:param alert_type: "error", "warning", "info" or "success".
:param aggregation_key: An arbitrary string to use for aggregation,
max length of 100 characters.
:param source_type_name: The type of event being posted.
'''
_initialize_connection(api_key, app_key)
if title is None:
raise SaltInvocationError('title must be specified')
if text is None:
raise SaltInvocationError('text must be specified')
if alert_type not in [None, 'error', 'warning', 'info', 'success']:
# Datadog only supports these alert types but the API doesn't return an
# error for an incorrect alert_type, so we can do it here for now.
# https://github.com/DataDog/datadogpy/issues/215
message = ('alert_type must be one of "error", "warning", "info", or '
'"success"')
raise SaltInvocationError(message)
ret = {'result': False,
'response': None,
'comment': ''}
try:
response = datadog.api.Event.create(title=title,
text=text,
date_happened=date_happened,
priority=priority,
host=host,
tags=tags,
alert_type=alert_type,
aggregation_key=aggregation_key,
source_type_name=source_type_name
)
except ValueError:
comment = ('Unexpected exception in Datadog Post Event API '
'call. Are your keys correct?')
ret['comment'] = comment
return ret
ret['response'] = response
if 'status' in response.keys():
ret['result'] = True
ret['comment'] = 'Successfully sent event'
else:
ret['comment'] = 'Error in posting event.'
return ret | [
"def",
"post_event",
"(",
"api_key",
"=",
"None",
",",
"app_key",
"=",
"None",
",",
"title",
"=",
"None",
",",
"text",
"=",
"None",
",",
"date_happened",
"=",
"None",
",",
"priority",
"=",
"None",
",",
"host",
"=",
"None",
",",
"tags",
"=",
"None",
... | Post an event to the Datadog stream.
CLI Example
.. code-block:: bash
salt-call datadog.post_event api_key='0123456789' \\
app_key='9876543210' \\
title='Salt Highstate' \\
text="Salt highstate was run on $(salt-call grains.get id)" \\
tags='["service:salt", "event:highstate"]'
Required arguments
:param title: The event title. Limited to 100 characters.
:param text: The body of the event. Limited to 4000 characters. The text
supports markdown.
Optional arguments
:param date_happened: POSIX timestamp of the event.
:param priority: The priority of the event ('normal' or 'low').
:param host: Host name to associate with the event.
:param tags: A list of tags to apply to the event.
:param alert_type: "error", "warning", "info" or "success".
:param aggregation_key: An arbitrary string to use for aggregation,
max length of 100 characters.
:param source_type_name: The type of event being posted. | [
"Post",
"an",
"event",
"to",
"the",
"Datadog",
"stream",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/datadog_api.py#L183-L264 | train |
saltstack/salt | salt/modules/xbpspkg.py | _get_version | def _get_version():
'''
Get the xbps version
'''
version_string = __salt__['cmd.run'](
[_check_xbps(), '--version'],
output_loglevel='trace')
if version_string is None:
# Dunno why it would, but...
return False
VERSION_MATCH = re.compile(r'(?:XBPS:[\s]+)([\d.]+)(?:[\s]+.*)')
version_match = VERSION_MATCH.search(version_string)
if not version_match:
return False
return version_match.group(1).split('.') | python | def _get_version():
'''
Get the xbps version
'''
version_string = __salt__['cmd.run'](
[_check_xbps(), '--version'],
output_loglevel='trace')
if version_string is None:
# Dunno why it would, but...
return False
VERSION_MATCH = re.compile(r'(?:XBPS:[\s]+)([\d.]+)(?:[\s]+.*)')
version_match = VERSION_MATCH.search(version_string)
if not version_match:
return False
return version_match.group(1).split('.') | [
"def",
"_get_version",
"(",
")",
":",
"version_string",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"[",
"_check_xbps",
"(",
")",
",",
"'--version'",
"]",
",",
"output_loglevel",
"=",
"'trace'",
")",
"if",
"version_string",
"is",
"None",
":",
"# Dunno why i... | Get the xbps version | [
"Get",
"the",
"xbps",
"version"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L51-L67 | train |
saltstack/salt | salt/modules/xbpspkg.py | list_pkgs | def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]):
return {}
cmd = 'xbps-query -l'
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if not line:
continue
try:
# xbps-query -l output sample:
# ii desktop-file-utils-0.22_4 Utilities to ...
#
# XXX handle package status (like 'ii') ?
pkg, ver = line.split(None)[1].rsplit('-', 1)
except ValueError:
log.error(
'xbps-query: Unexpected formatting in line: "%s"',
line
)
__salt__['pkg_resource.add_pkg'](ret, pkg, ver)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret | python | def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
'''
versions_as_list = salt.utils.data.is_true(versions_as_list)
# not yet implemented or not applicable
if any([salt.utils.data.is_true(kwargs.get(x)) for x in ('removed', 'purge_desired')]):
return {}
cmd = 'xbps-query -l'
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if not line:
continue
try:
# xbps-query -l output sample:
# ii desktop-file-utils-0.22_4 Utilities to ...
#
# XXX handle package status (like 'ii') ?
pkg, ver = line.split(None)[1].rsplit('-', 1)
except ValueError:
log.error(
'xbps-query: Unexpected formatting in line: "%s"',
line
)
__salt__['pkg_resource.add_pkg'](ret, pkg, ver)
__salt__['pkg_resource.sort_pkglist'](ret)
if not versions_as_list:
__salt__['pkg_resource.stringify'](ret)
return ret | [
"def",
"list_pkgs",
"(",
"versions_as_list",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"versions_as_list",
"=",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"versions_as_list",
")",
"# not yet implemented or not applicable",
"if",
"any",
"(",
... | List the packages currently installed as a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs | [
"List",
"the",
"packages",
"currently",
"installed",
"as",
"a",
"dict",
"::"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L81-L121 | train |
saltstack/salt | salt/modules/xbpspkg.py | list_upgrades | def list_upgrades(refresh=True, **kwargs):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
# sample output of 'xbps-install -un':
# fuse-2.9.4_4 update i686 http://repo.voidlinux.eu/current 298133 91688
# xtools-0.34_1 update noarch http://repo.voidlinux.eu/current 21424 10752
refresh = salt.utils.data.is_true(refresh)
# Refresh repo index before checking for latest version available
if refresh:
refresh_db()
ret = {}
# retrieve list of updatable packages
cmd = 'xbps-install -un'
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if not line:
continue
pkg = "base-system"
ver = "NonNumericValueIsError"
try:
pkg, ver = line.split()[0].rsplit('-', 1)
except (ValueError, IndexError):
log.error(
'xbps-query: Unexpected formatting in line: "%s"',
line
)
continue
log.trace('pkg=%s version=%s', pkg, ver)
ret[pkg] = ver
return ret | python | def list_upgrades(refresh=True, **kwargs):
'''
Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
# sample output of 'xbps-install -un':
# fuse-2.9.4_4 update i686 http://repo.voidlinux.eu/current 298133 91688
# xtools-0.34_1 update noarch http://repo.voidlinux.eu/current 21424 10752
refresh = salt.utils.data.is_true(refresh)
# Refresh repo index before checking for latest version available
if refresh:
refresh_db()
ret = {}
# retrieve list of updatable packages
cmd = 'xbps-install -un'
out = __salt__['cmd.run'](cmd, output_loglevel='trace')
for line in out.splitlines():
if not line:
continue
pkg = "base-system"
ver = "NonNumericValueIsError"
try:
pkg, ver = line.split()[0].rsplit('-', 1)
except (ValueError, IndexError):
log.error(
'xbps-query: Unexpected formatting in line: "%s"',
line
)
continue
log.trace('pkg=%s version=%s', pkg, ver)
ret[pkg] = ver
return ret | [
"def",
"list_upgrades",
"(",
"refresh",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# sample output of 'xbps-install -un':",
"# fuse-2.9.4_4 update i686 http://repo.voidlinux.eu/current 298133 91688",
"# xtools-0.34_1 update noarch http://repo.voidlinux.eu/current 21424 1075... | Check whether or not an upgrade is available for all packages
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades | [
"Check",
"whether",
"or",
"not",
"an",
"upgrade",
"is",
"available",
"for",
"all",
"packages"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L124-L167 | train |
saltstack/salt | salt/modules/xbpspkg.py | refresh_db | def refresh_db(**kwargs):
'''
Update list of available packages from installed repos
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
cmd = 'xbps-install -Sy'
call = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
return True | python | def refresh_db(**kwargs):
'''
Update list of available packages from installed repos
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
cmd = 'xbps-install -Sy'
call = __salt__['cmd.run_all'](cmd, output_loglevel='trace')
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
raise CommandExecutionError(comment)
return True | [
"def",
"refresh_db",
"(",
"*",
"*",
"kwargs",
")",
":",
"# Remove rtag file to keep multiple refreshes from happening in pkg states",
"salt",
".",
"utils",
".",
"pkg",
".",
"clear_rtag",
"(",
"__opts__",
")",
"cmd",
"=",
"'xbps-install -Sy'",
"call",
"=",
"__salt__",
... | Update list of available packages from installed repos
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db | [
"Update",
"list",
"of",
"available",
"packages",
"from",
"installed",
"repos"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L263-L284 | train |
saltstack/salt | salt/modules/xbpspkg.py | install | def install(name=None, refresh=False, fromrepo=None,
pkgs=None, sources=None, **kwargs):
'''
Install the passed package
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo
Specify a package repository (url) to install from.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo","bar"]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
# XXX sources is not yet used in this code
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if pkg_type != 'repository':
log.error('xbps: pkg_type "%s" not supported.', pkg_type)
return {}
cmd = ['xbps-install']
if refresh:
cmd.append('-S') # update repo db
if fromrepo:
cmd.append('--repository={0}'.format(fromrepo))
cmd.append('-y') # assume yes when asked
cmd.extend(pkg_params)
old = list_pkgs()
__salt__['cmd.run'](cmd, output_loglevel='trace')
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
return salt.utils.data.compare_dicts(old, new) | python | def install(name=None, refresh=False, fromrepo=None,
pkgs=None, sources=None, **kwargs):
'''
Install the passed package
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo
Specify a package repository (url) to install from.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo","bar"]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
'''
# XXX sources is not yet used in this code
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if pkg_type != 'repository':
log.error('xbps: pkg_type "%s" not supported.', pkg_type)
return {}
cmd = ['xbps-install']
if refresh:
cmd.append('-S') # update repo db
if fromrepo:
cmd.append('--repository={0}'.format(fromrepo))
cmd.append('-y') # assume yes when asked
cmd.extend(pkg_params)
old = list_pkgs()
__salt__['cmd.run'](cmd, output_loglevel='trace')
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
_rehash()
return salt.utils.data.compare_dicts(old, new) | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"fromrepo",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"sources",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# XXX sources is not yet used in this code",
"try",
":",
"p... | Install the passed package
name
The name of the package to be installed.
refresh
Whether or not to refresh the package database before installing.
fromrepo
Specify a package repository (url) to install from.
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo","bar"]'
sources
A list of packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
Return a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name> | [
"Install",
"the",
"passed",
"package"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L349-L430 | train |
saltstack/salt | salt/modules/xbpspkg.py | remove | def remove(name=None, pkgs=None, recursive=True, **kwargs):
'''
name
The name of the package to be deleted.
recursive
Also remove dependent packages (not required elsewhere).
Default mode: enabled.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a list containing the removed packages.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name> [recursive=False]
salt '*' pkg.remove <package1>,<package2>,<package3> [recursive=False]
salt '*' pkg.remove pkgs='["foo", "bar"]' [recursive=False]
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
old = list_pkgs()
# keep only installed packages
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
cmd = ['xbps-remove', '-y']
if recursive:
cmd.append('-R')
cmd.extend(targets)
__salt__['cmd.run'](cmd, output_loglevel='trace')
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | python | def remove(name=None, pkgs=None, recursive=True, **kwargs):
'''
name
The name of the package to be deleted.
recursive
Also remove dependent packages (not required elsewhere).
Default mode: enabled.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a list containing the removed packages.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name> [recursive=False]
salt '*' pkg.remove <package1>,<package2>,<package3> [recursive=False]
salt '*' pkg.remove pkgs='["foo", "bar"]' [recursive=False]
'''
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs
)
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
old = list_pkgs()
# keep only installed packages
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
cmd = ['xbps-remove', '-y']
if recursive:
cmd.append('-R')
cmd.extend(targets)
__salt__['cmd.run'](cmd, output_loglevel='trace')
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | [
"def",
"remove",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pkg_params",
",",
"pkg_type",
"=",
"__salt__",
"[",
"'pkg_resource.parse_targets'",
"]",
"(",
"name",
",... | name
The name of the package to be deleted.
recursive
Also remove dependent packages (not required elsewhere).
Default mode: enabled.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a list containing the removed packages.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name> [recursive=False]
salt '*' pkg.remove <package1>,<package2>,<package3> [recursive=False]
salt '*' pkg.remove pkgs='["foo", "bar"]' [recursive=False] | [
"name",
"The",
"name",
"of",
"the",
"package",
"to",
"be",
"deleted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L433-L484 | train |
saltstack/salt | salt/modules/xbpspkg.py | list_repos | def list_repos(**kwargs):
'''
List all repos known by XBPS
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
out = __salt__['cmd.run']('xbps-query -L', output_loglevel='trace')
for line in out.splitlines():
repo = {}
if not line:
continue
try:
nb, url, rsa = line.strip().split(' ', 2)
except ValueError:
log.error(
'Problem parsing xbps-query: '
'Unexpected formatting in line: "%s"', line
)
repo['nbpkg'] = int(nb) if nb.isdigit() else 0
repo['url'] = url
repo['rsasigned'] = True if rsa == '(RSA signed)' else False
repos[repo['url']] = repo
return repos | python | def list_repos(**kwargs):
'''
List all repos known by XBPS
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
out = __salt__['cmd.run']('xbps-query -L', output_loglevel='trace')
for line in out.splitlines():
repo = {}
if not line:
continue
try:
nb, url, rsa = line.strip().split(' ', 2)
except ValueError:
log.error(
'Problem parsing xbps-query: '
'Unexpected formatting in line: "%s"', line
)
repo['nbpkg'] = int(nb) if nb.isdigit() else 0
repo['url'] = url
repo['rsasigned'] = True if rsa == '(RSA signed)' else False
repos[repo['url']] = repo
return repos | [
"def",
"list_repos",
"(",
"*",
"*",
"kwargs",
")",
":",
"repos",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'xbps-query -L'",
",",
"output_loglevel",
"=",
"'trace'",
")",
"for",
"line",
"in",
"out",
".",
"splitlines",
"(",
")",... | List all repos known by XBPS
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos | [
"List",
"all",
"repos",
"known",
"by",
"XBPS"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L487-L514 | train |
saltstack/salt | salt/modules/xbpspkg.py | _locate_repo_files | def _locate_repo_files(repo, rewrite=False):
'''
Find what file a repo is called in.
Helper function for add_repo() and del_repo()
repo
url of the repo to locate (persistent).
rewrite
Whether to remove matching repository settings during this process.
Returns a list of absolute paths.
'''
ret_val = []
files = []
conf_dirs = ['/etc/xbps.d/', '/usr/share/xbps.d/']
name_glob = '*.conf'
# Matches a line where first printing is "repository" and there is an equals
# sign before the repo, an optional forwardslash at the end of the repo name,
# and it's possible for there to be a comment after repository=repo
regex = re.compile(r'\s*repository\s*=\s*'+repo+r'/?\s*(#.*)?$')
for cur_dir in conf_dirs:
files.extend(glob.glob(cur_dir+name_glob))
for filename in files:
write_buff = []
with salt.utils.files.fopen(filename, 'r') as cur_file:
for line in cur_file:
if regex.match(salt.utils.stringutils.to_unicode(line)):
ret_val.append(filename)
else:
write_buff.append(line)
if rewrite and filename in ret_val:
if write_buff:
with salt.utils.files.fopen(filename, 'w') as rewrite_file:
rewrite_file.writelines(write_buff)
else: # Prune empty files
os.remove(filename)
return ret_val | python | def _locate_repo_files(repo, rewrite=False):
'''
Find what file a repo is called in.
Helper function for add_repo() and del_repo()
repo
url of the repo to locate (persistent).
rewrite
Whether to remove matching repository settings during this process.
Returns a list of absolute paths.
'''
ret_val = []
files = []
conf_dirs = ['/etc/xbps.d/', '/usr/share/xbps.d/']
name_glob = '*.conf'
# Matches a line where first printing is "repository" and there is an equals
# sign before the repo, an optional forwardslash at the end of the repo name,
# and it's possible for there to be a comment after repository=repo
regex = re.compile(r'\s*repository\s*=\s*'+repo+r'/?\s*(#.*)?$')
for cur_dir in conf_dirs:
files.extend(glob.glob(cur_dir+name_glob))
for filename in files:
write_buff = []
with salt.utils.files.fopen(filename, 'r') as cur_file:
for line in cur_file:
if regex.match(salt.utils.stringutils.to_unicode(line)):
ret_val.append(filename)
else:
write_buff.append(line)
if rewrite and filename in ret_val:
if write_buff:
with salt.utils.files.fopen(filename, 'w') as rewrite_file:
rewrite_file.writelines(write_buff)
else: # Prune empty files
os.remove(filename)
return ret_val | [
"def",
"_locate_repo_files",
"(",
"repo",
",",
"rewrite",
"=",
"False",
")",
":",
"ret_val",
"=",
"[",
"]",
"files",
"=",
"[",
"]",
"conf_dirs",
"=",
"[",
"'/etc/xbps.d/'",
",",
"'/usr/share/xbps.d/'",
"]",
"name_glob",
"=",
"'*.conf'",
"# Matches a line where... | Find what file a repo is called in.
Helper function for add_repo() and del_repo()
repo
url of the repo to locate (persistent).
rewrite
Whether to remove matching repository settings during this process.
Returns a list of absolute paths. | [
"Find",
"what",
"file",
"a",
"repo",
"is",
"called",
"in",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L533-L575 | train |
saltstack/salt | salt/modules/xbpspkg.py | add_repo | def add_repo(repo, conffile='/usr/share/xbps.d/15-saltstack.conf'):
'''
Add an XBPS repository to the system.
repo
url of repo to add (persistent).
conffile
path to xbps conf file to add this repo
default: /usr/share/xbps.d/15-saltstack.conf
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo <repo url> [conffile=/path/to/xbps/repo.conf]
'''
if not _locate_repo_files(repo):
try:
with salt.utils.files.fopen(conffile, 'a+') as conf_file:
conf_file.write(
salt.utils.stringutils.to_str(
'repository={0}\n'.format(repo)
)
)
except IOError:
return False
return True | python | def add_repo(repo, conffile='/usr/share/xbps.d/15-saltstack.conf'):
'''
Add an XBPS repository to the system.
repo
url of repo to add (persistent).
conffile
path to xbps conf file to add this repo
default: /usr/share/xbps.d/15-saltstack.conf
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo <repo url> [conffile=/path/to/xbps/repo.conf]
'''
if not _locate_repo_files(repo):
try:
with salt.utils.files.fopen(conffile, 'a+') as conf_file:
conf_file.write(
salt.utils.stringutils.to_str(
'repository={0}\n'.format(repo)
)
)
except IOError:
return False
return True | [
"def",
"add_repo",
"(",
"repo",
",",
"conffile",
"=",
"'/usr/share/xbps.d/15-saltstack.conf'",
")",
":",
"if",
"not",
"_locate_repo_files",
"(",
"repo",
")",
":",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"conffile",
",",
"... | Add an XBPS repository to the system.
repo
url of repo to add (persistent).
conffile
path to xbps conf file to add this repo
default: /usr/share/xbps.d/15-saltstack.conf
CLI Examples:
.. code-block:: bash
salt '*' pkg.add_repo <repo url> [conffile=/path/to/xbps/repo.conf] | [
"Add",
"an",
"XBPS",
"repository",
"to",
"the",
"system",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L578-L607 | train |
saltstack/salt | salt/modules/xbpspkg.py | del_repo | def del_repo(repo, **kwargs):
'''
Remove an XBPS repository from the system.
repo
url of repo to remove (persistent).
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo <repo url>
'''
try:
_locate_repo_files(repo, rewrite=True)
except IOError:
return False
else:
return True | python | def del_repo(repo, **kwargs):
'''
Remove an XBPS repository from the system.
repo
url of repo to remove (persistent).
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo <repo url>
'''
try:
_locate_repo_files(repo, rewrite=True)
except IOError:
return False
else:
return True | [
"def",
"del_repo",
"(",
"repo",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"_locate_repo_files",
"(",
"repo",
",",
"rewrite",
"=",
"True",
")",
"except",
"IOError",
":",
"return",
"False",
"else",
":",
"return",
"True"
] | Remove an XBPS repository from the system.
repo
url of repo to remove (persistent).
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo <repo url> | [
"Remove",
"an",
"XBPS",
"repository",
"from",
"the",
"system",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/xbpspkg.py#L610-L629 | train |
saltstack/salt | salt/states/apache_conf.py | enabled | def enabled(name):
'''
Ensure an Apache conf is enabled.
name
Name of the Apache conf
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_enabled = __salt__['apache.check_conf_enabled'](name)
if not is_enabled:
if __opts__['test']:
msg = 'Apache conf {0} is set to be enabled.'.format(name)
ret['comment'] = msg
ret['changes']['old'] = None
ret['changes']['new'] = name
ret['result'] = None
return ret
status = __salt__['apache.a2enconf'](name)['Status']
if isinstance(status, six.string_types) and 'enabled' in status:
ret['result'] = True
ret['changes']['old'] = None
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to enable {0} Apache conf'.format(name)
if isinstance(status, six.string_types):
ret['comment'] = ret['comment'] + ' ({0})'.format(status)
return ret
else:
ret['comment'] = '{0} already enabled.'.format(name)
return ret | python | def enabled(name):
'''
Ensure an Apache conf is enabled.
name
Name of the Apache conf
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
is_enabled = __salt__['apache.check_conf_enabled'](name)
if not is_enabled:
if __opts__['test']:
msg = 'Apache conf {0} is set to be enabled.'.format(name)
ret['comment'] = msg
ret['changes']['old'] = None
ret['changes']['new'] = name
ret['result'] = None
return ret
status = __salt__['apache.a2enconf'](name)['Status']
if isinstance(status, six.string_types) and 'enabled' in status:
ret['result'] = True
ret['changes']['old'] = None
ret['changes']['new'] = name
else:
ret['result'] = False
ret['comment'] = 'Failed to enable {0} Apache conf'.format(name)
if isinstance(status, six.string_types):
ret['comment'] = ret['comment'] + ' ({0})'.format(status)
return ret
else:
ret['comment'] = '{0} already enabled.'.format(name)
return ret | [
"def",
"enabled",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"is_enabled",
"=",
"__salt__",
"[",
"'apache.check_conf_enabled'",
"]",
"(... | Ensure an Apache conf is enabled.
name
Name of the Apache conf | [
"Ensure",
"an",
"Apache",
"conf",
"is",
"enabled",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/apache_conf.py#L33-L64 | train |
saltstack/salt | salt/modules/napalm_ntp.py | peers | def peers(**kwargs): # pylint: disable=unused-argument
'''
Returns a list the NTP peers configured on the network device.
:return: configured NTP peers as list.
CLI Example:
.. code-block:: bash
salt '*' ntp.peers
Example output:
.. code-block:: python
[
'192.168.0.1',
'172.17.17.1',
'172.17.17.2',
'2400:cb00:6:1024::c71b:840a'
]
'''
ntp_peers = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_ntp_peers',
**{
}
)
if not ntp_peers.get('result'):
return ntp_peers
ntp_peers_list = list(ntp_peers.get('out', {}).keys())
ntp_peers['out'] = ntp_peers_list
return ntp_peers | python | def peers(**kwargs): # pylint: disable=unused-argument
'''
Returns a list the NTP peers configured on the network device.
:return: configured NTP peers as list.
CLI Example:
.. code-block:: bash
salt '*' ntp.peers
Example output:
.. code-block:: python
[
'192.168.0.1',
'172.17.17.1',
'172.17.17.2',
'2400:cb00:6:1024::c71b:840a'
]
'''
ntp_peers = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_ntp_peers',
**{
}
)
if not ntp_peers.get('result'):
return ntp_peers
ntp_peers_list = list(ntp_peers.get('out', {}).keys())
ntp_peers['out'] = ntp_peers_list
return ntp_peers | [
"def",
"peers",
"(",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"ntp_peers",
"=",
"salt",
".",
"utils",
".",
"napalm",
".",
"call",
"(",
"napalm_device",
",",
"# pylint: disable=undefined-variable",
"'get_ntp_peers'",
",",
"*",
"*",
"{",
... | Returns a list the NTP peers configured on the network device.
:return: configured NTP peers as list.
CLI Example:
.. code-block:: bash
salt '*' ntp.peers
Example output:
.. code-block:: python
[
'192.168.0.1',
'172.17.17.1',
'172.17.17.2',
'2400:cb00:6:1024::c71b:840a'
] | [
"Returns",
"a",
"list",
"the",
"NTP",
"peers",
"configured",
"on",
"the",
"network",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_ntp.py#L63-L103 | train |
saltstack/salt | salt/modules/napalm_ntp.py | servers | def servers(**kwargs): # pylint: disable=unused-argument
'''
Returns a list of the configured NTP servers on the device.
CLI Example:
.. code-block:: bash
salt '*' ntp.servers
Example output:
.. code-block:: python
[
'192.168.0.1',
'172.17.17.1',
'172.17.17.2',
'2400:cb00:6:1024::c71b:840a'
]
'''
ntp_servers = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_ntp_servers',
**{
}
)
if not ntp_servers.get('result'):
return ntp_servers
ntp_servers_list = list(ntp_servers.get('out', {}).keys())
ntp_servers['out'] = ntp_servers_list
return ntp_servers | python | def servers(**kwargs): # pylint: disable=unused-argument
'''
Returns a list of the configured NTP servers on the device.
CLI Example:
.. code-block:: bash
salt '*' ntp.servers
Example output:
.. code-block:: python
[
'192.168.0.1',
'172.17.17.1',
'172.17.17.2',
'2400:cb00:6:1024::c71b:840a'
]
'''
ntp_servers = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_ntp_servers',
**{
}
)
if not ntp_servers.get('result'):
return ntp_servers
ntp_servers_list = list(ntp_servers.get('out', {}).keys())
ntp_servers['out'] = ntp_servers_list
return ntp_servers | [
"def",
"servers",
"(",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"ntp_servers",
"=",
"salt",
".",
"utils",
".",
"napalm",
".",
"call",
"(",
"napalm_device",
",",
"# pylint: disable=undefined-variable",
"'get_ntp_servers'",
",",
"*",
"*",
"... | Returns a list of the configured NTP servers on the device.
CLI Example:
.. code-block:: bash
salt '*' ntp.servers
Example output:
.. code-block:: python
[
'192.168.0.1',
'172.17.17.1',
'172.17.17.2',
'2400:cb00:6:1024::c71b:840a'
] | [
"Returns",
"a",
"list",
"of",
"the",
"configured",
"NTP",
"servers",
"on",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_ntp.py#L107-L144 | train |
saltstack/salt | salt/modules/napalm_ntp.py | stats | def stats(peer=None, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary containing synchronization details of the NTP peers.
:param peer: Returns only the details of a specific NTP peer.
:return: a list of dictionaries, with the following keys:
* remote
* referenceid
* synchronized
* stratum
* type
* when
* hostpoll
* reachability
* delay
* offset
* jitter
CLI Example:
.. code-block:: bash
salt '*' ntp.stats
Example output:
.. code-block:: python
[
{
'remote' : '188.114.101.4',
'referenceid' : '188.114.100.1',
'synchronized' : True,
'stratum' : 4,
'type' : '-',
'when' : '107',
'hostpoll' : 256,
'reachability' : 377,
'delay' : 164.228,
'offset' : -13.866,
'jitter' : 2.695
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_ntp_stats',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
ntp_peers = proxy_output.get('out')
if peer:
ntp_peers = [ntp_peer for ntp_peer in ntp_peers if ntp_peer.get('remote', '') == peer]
proxy_output.update({
'out': ntp_peers
})
return proxy_output | python | def stats(peer=None, **kwargs): # pylint: disable=unused-argument
'''
Returns a dictionary containing synchronization details of the NTP peers.
:param peer: Returns only the details of a specific NTP peer.
:return: a list of dictionaries, with the following keys:
* remote
* referenceid
* synchronized
* stratum
* type
* when
* hostpoll
* reachability
* delay
* offset
* jitter
CLI Example:
.. code-block:: bash
salt '*' ntp.stats
Example output:
.. code-block:: python
[
{
'remote' : '188.114.101.4',
'referenceid' : '188.114.100.1',
'synchronized' : True,
'stratum' : 4,
'type' : '-',
'when' : '107',
'hostpoll' : 256,
'reachability' : 377,
'delay' : 164.228,
'offset' : -13.866,
'jitter' : 2.695
}
]
'''
proxy_output = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
'get_ntp_stats',
**{
}
)
if not proxy_output.get('result'):
return proxy_output
ntp_peers = proxy_output.get('out')
if peer:
ntp_peers = [ntp_peer for ntp_peer in ntp_peers if ntp_peer.get('remote', '') == peer]
proxy_output.update({
'out': ntp_peers
})
return proxy_output | [
"def",
"stats",
"(",
"peer",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"proxy_output",
"=",
"salt",
".",
"utils",
".",
"napalm",
".",
"call",
"(",
"napalm_device",
",",
"# pylint: disable=undefined-variable",
"'get_ntp_st... | Returns a dictionary containing synchronization details of the NTP peers.
:param peer: Returns only the details of a specific NTP peer.
:return: a list of dictionaries, with the following keys:
* remote
* referenceid
* synchronized
* stratum
* type
* when
* hostpoll
* reachability
* delay
* offset
* jitter
CLI Example:
.. code-block:: bash
salt '*' ntp.stats
Example output:
.. code-block:: python
[
{
'remote' : '188.114.101.4',
'referenceid' : '188.114.100.1',
'synchronized' : True,
'stratum' : 4,
'type' : '-',
'when' : '107',
'hostpoll' : 256,
'reachability' : 377,
'delay' : 164.228,
'offset' : -13.866,
'jitter' : 2.695
}
] | [
"Returns",
"a",
"dictionary",
"containing",
"synchronization",
"details",
"of",
"the",
"NTP",
"peers",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_ntp.py#L148-L214 | train |
saltstack/salt | salt/modules/napalm_ntp.py | set_peers | def set_peers(*peers, **options):
'''
Configures a list of NTP peers on the device.
:param peers: list of IP Addresses/Domain Names
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:commit commit (bool): commit loaded config. By default ``commit`` is True
(will commit the changes). Useful when the user does not want to commit
after each change, but after a couple.
By default this function will commit the config changes (if any). To load without committing, use the `commit`
option. For dry run use the `test` argument.
CLI Example:
.. code-block:: bash
salt '*' ntp.set_peers 192.168.0.1 172.17.17.1 time.apple.com
salt '*' ntp.set_peers 172.17.17.1 test=True # only displays the diff
salt '*' ntp.set_peers 192.168.0.1 commit=False # preserves the changes, but does not commit
'''
test = options.pop('test', False)
commit = options.pop('commit', True)
return __salt__['net.load_template']('set_ntp_peers',
peers=peers,
test=test,
commit=commit,
inherit_napalm_device=napalm_device) | python | def set_peers(*peers, **options):
'''
Configures a list of NTP peers on the device.
:param peers: list of IP Addresses/Domain Names
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:commit commit (bool): commit loaded config. By default ``commit`` is True
(will commit the changes). Useful when the user does not want to commit
after each change, but after a couple.
By default this function will commit the config changes (if any). To load without committing, use the `commit`
option. For dry run use the `test` argument.
CLI Example:
.. code-block:: bash
salt '*' ntp.set_peers 192.168.0.1 172.17.17.1 time.apple.com
salt '*' ntp.set_peers 172.17.17.1 test=True # only displays the diff
salt '*' ntp.set_peers 192.168.0.1 commit=False # preserves the changes, but does not commit
'''
test = options.pop('test', False)
commit = options.pop('commit', True)
return __salt__['net.load_template']('set_ntp_peers',
peers=peers,
test=test,
commit=commit,
inherit_napalm_device=napalm_device) | [
"def",
"set_peers",
"(",
"*",
"peers",
",",
"*",
"*",
"options",
")",
":",
"test",
"=",
"options",
".",
"pop",
"(",
"'test'",
",",
"False",
")",
"commit",
"=",
"options",
".",
"pop",
"(",
"'commit'",
",",
"True",
")",
"return",
"__salt__",
"[",
"'n... | Configures a list of NTP peers on the device.
:param peers: list of IP Addresses/Domain Names
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:commit commit (bool): commit loaded config. By default ``commit`` is True
(will commit the changes). Useful when the user does not want to commit
after each change, but after a couple.
By default this function will commit the config changes (if any). To load without committing, use the `commit`
option. For dry run use the `test` argument.
CLI Example:
.. code-block:: bash
salt '*' ntp.set_peers 192.168.0.1 172.17.17.1 time.apple.com
salt '*' ntp.set_peers 172.17.17.1 test=True # only displays the diff
salt '*' ntp.set_peers 192.168.0.1 commit=False # preserves the changes, but does not commit | [
"Configures",
"a",
"list",
"of",
"NTP",
"peers",
"on",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_ntp.py#L218-L249 | train |
saltstack/salt | salt/modules/napalm_ntp.py | delete_servers | def delete_servers(*servers, **options):
'''
Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:param commit (bool): commit loaded config. By default ``commit`` is True
(will commit the changes). Useful when the user does not want to commit
after each change, but after a couple.
By default this function will commit the config changes (if any). To load
without committing, use the ``commit`` option. For dry run use the ``test``
argument.
CLI Example:
.. code-block:: bash
salt '*' ntp.delete_servers 8.8.8.8 time.apple.com
salt '*' ntp.delete_servers 172.17.17.1 test=True # only displays the diff
salt '*' ntp.delete_servers 192.168.0.1 commit=False # preserves the changes, but does not commit
'''
test = options.pop('test', False)
commit = options.pop('commit', True)
return __salt__['net.load_template']('delete_ntp_servers',
servers=servers,
test=test,
commit=commit,
inherit_napalm_device=napalm_device) | python | def delete_servers(*servers, **options):
'''
Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:param commit (bool): commit loaded config. By default ``commit`` is True
(will commit the changes). Useful when the user does not want to commit
after each change, but after a couple.
By default this function will commit the config changes (if any). To load
without committing, use the ``commit`` option. For dry run use the ``test``
argument.
CLI Example:
.. code-block:: bash
salt '*' ntp.delete_servers 8.8.8.8 time.apple.com
salt '*' ntp.delete_servers 172.17.17.1 test=True # only displays the diff
salt '*' ntp.delete_servers 192.168.0.1 commit=False # preserves the changes, but does not commit
'''
test = options.pop('test', False)
commit = options.pop('commit', True)
return __salt__['net.load_template']('delete_ntp_servers',
servers=servers,
test=test,
commit=commit,
inherit_napalm_device=napalm_device) | [
"def",
"delete_servers",
"(",
"*",
"servers",
",",
"*",
"*",
"options",
")",
":",
"test",
"=",
"options",
".",
"pop",
"(",
"'test'",
",",
"False",
")",
"commit",
"=",
"options",
".",
"pop",
"(",
"'commit'",
",",
"True",
")",
"return",
"__salt__",
"["... | Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:param commit (bool): commit loaded config. By default ``commit`` is True
(will commit the changes). Useful when the user does not want to commit
after each change, but after a couple.
By default this function will commit the config changes (if any). To load
without committing, use the ``commit`` option. For dry run use the ``test``
argument.
CLI Example:
.. code-block:: bash
salt '*' ntp.delete_servers 8.8.8.8 time.apple.com
salt '*' ntp.delete_servers 172.17.17.1 test=True # only displays the diff
salt '*' ntp.delete_servers 192.168.0.1 commit=False # preserves the changes, but does not commit | [
"Removes",
"NTP",
"servers",
"configured",
"on",
"the",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/napalm_ntp.py#L323-L356 | train |
saltstack/salt | salt/returners/elasticsearch_return.py | returner | def returner(ret):
'''
Process the return from Salt
'''
job_fun = ret['fun']
job_fun_escaped = job_fun.replace('.', '_')
job_id = ret['jid']
job_retcode = ret.get('retcode', 1)
job_success = True if not job_retcode else False
options = _get_options(ret)
if job_fun in options['functions_blacklist']:
log.info(
'Won\'t push new data to Elasticsearch, job with jid=%s and '
'function=%s which is in the user-defined list of ignored '
'functions', job_id, job_fun
)
return
if ret.get('data', None) is None and ret.get('return') is None:
log.info(
'Won\'t push new data to Elasticsearch, job with jid=%s was '
'not successful', job_id
)
return
# Build the index name
if options['states_single_index'] and job_fun in STATE_FUNCTIONS:
index = 'salt-{0}'.format(STATE_FUNCTIONS[job_fun])
else:
index = 'salt-{0}'.format(job_fun_escaped)
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
counts = {}
# Do some special processing for state returns
if job_fun in STATE_FUNCTIONS:
# Init the state counts
if options['states_count']:
counts = {
'suceeded': 0,
'failed': 0,
}
# Prepend each state execution key in ret['data'] with a zero-padded
# version of the '__run_num__' field allowing the states to be ordered
# more easily. Change the index to be
# index to be '<index>-ordered' so as not to clash with the unsorted
# index data format
if options['states_order_output'] and isinstance(ret['data'], dict):
index = '{0}-ordered'.format(index)
max_chars = len(six.text_type(len(ret['data'])))
for uid, data in six.iteritems(ret['data']):
# Skip keys we've already prefixed
if uid.startswith(tuple('0123456789')):
continue
# Store the function being called as it's a useful key to search
decoded_uid = uid.split('_|-')
ret['data'][uid]['_func'] = '{0}.{1}'.format(
decoded_uid[0],
decoded_uid[-1]
)
# Prefix the key with the run order so it can be sorted
new_uid = '{0}_|-{1}'.format(
six.text_type(data['__run_num__']).zfill(max_chars),
uid,
)
ret['data'][new_uid] = ret['data'].pop(uid)
# Catch a state output that has failed and where the error message is
# not in a dict as expected. This prevents elasticsearch from
# complaining about a mapping error
elif not isinstance(ret['data'], dict):
ret['data'] = {job_fun_escaped: {'return': ret['data']}}
# Need to count state successes and failures
if options['states_count']:
for state_data in ret['data'].values():
if state_data['result'] is False:
counts['failed'] += 1
else:
counts['suceeded'] += 1
# Ensure the index exists
_ensure_index(index)
# Build the payload
class UTC(tzinfo):
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return 'UTC'
def dst(self, dt):
return timedelta(0)
utc = UTC()
data = {
'@timestamp': datetime.datetime.now(utc).isoformat(),
'success': job_success,
'retcode': job_retcode,
'minion': ret['id'],
'fun': job_fun,
'jid': job_id,
'counts': counts,
'data': _convert_keys(ret['data'])
}
if options['debug_returner_payload']:
log.debug('elasicsearch payload: %s', data)
# Post the payload
ret = __salt__['elasticsearch.document_create'](index=index,
doc_type=options['doc_type'],
body=salt.utils.json.dumps(data)) | python | def returner(ret):
'''
Process the return from Salt
'''
job_fun = ret['fun']
job_fun_escaped = job_fun.replace('.', '_')
job_id = ret['jid']
job_retcode = ret.get('retcode', 1)
job_success = True if not job_retcode else False
options = _get_options(ret)
if job_fun in options['functions_blacklist']:
log.info(
'Won\'t push new data to Elasticsearch, job with jid=%s and '
'function=%s which is in the user-defined list of ignored '
'functions', job_id, job_fun
)
return
if ret.get('data', None) is None and ret.get('return') is None:
log.info(
'Won\'t push new data to Elasticsearch, job with jid=%s was '
'not successful', job_id
)
return
# Build the index name
if options['states_single_index'] and job_fun in STATE_FUNCTIONS:
index = 'salt-{0}'.format(STATE_FUNCTIONS[job_fun])
else:
index = 'salt-{0}'.format(job_fun_escaped)
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
counts = {}
# Do some special processing for state returns
if job_fun in STATE_FUNCTIONS:
# Init the state counts
if options['states_count']:
counts = {
'suceeded': 0,
'failed': 0,
}
# Prepend each state execution key in ret['data'] with a zero-padded
# version of the '__run_num__' field allowing the states to be ordered
# more easily. Change the index to be
# index to be '<index>-ordered' so as not to clash with the unsorted
# index data format
if options['states_order_output'] and isinstance(ret['data'], dict):
index = '{0}-ordered'.format(index)
max_chars = len(six.text_type(len(ret['data'])))
for uid, data in six.iteritems(ret['data']):
# Skip keys we've already prefixed
if uid.startswith(tuple('0123456789')):
continue
# Store the function being called as it's a useful key to search
decoded_uid = uid.split('_|-')
ret['data'][uid]['_func'] = '{0}.{1}'.format(
decoded_uid[0],
decoded_uid[-1]
)
# Prefix the key with the run order so it can be sorted
new_uid = '{0}_|-{1}'.format(
six.text_type(data['__run_num__']).zfill(max_chars),
uid,
)
ret['data'][new_uid] = ret['data'].pop(uid)
# Catch a state output that has failed and where the error message is
# not in a dict as expected. This prevents elasticsearch from
# complaining about a mapping error
elif not isinstance(ret['data'], dict):
ret['data'] = {job_fun_escaped: {'return': ret['data']}}
# Need to count state successes and failures
if options['states_count']:
for state_data in ret['data'].values():
if state_data['result'] is False:
counts['failed'] += 1
else:
counts['suceeded'] += 1
# Ensure the index exists
_ensure_index(index)
# Build the payload
class UTC(tzinfo):
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return 'UTC'
def dst(self, dt):
return timedelta(0)
utc = UTC()
data = {
'@timestamp': datetime.datetime.now(utc).isoformat(),
'success': job_success,
'retcode': job_retcode,
'minion': ret['id'],
'fun': job_fun,
'jid': job_id,
'counts': counts,
'data': _convert_keys(ret['data'])
}
if options['debug_returner_payload']:
log.debug('elasicsearch payload: %s', data)
# Post the payload
ret = __salt__['elasticsearch.document_create'](index=index,
doc_type=options['doc_type'],
body=salt.utils.json.dumps(data)) | [
"def",
"returner",
"(",
"ret",
")",
":",
"job_fun",
"=",
"ret",
"[",
"'fun'",
"]",
"job_fun_escaped",
"=",
"job_fun",
".",
"replace",
"(",
"'.'",
",",
"'_'",
")",
"job_id",
"=",
"ret",
"[",
"'jid'",
"]",
"job_retcode",
"=",
"ret",
".",
"get",
"(",
... | Process the return from Salt | [
"Process",
"the",
"return",
"from",
"Salt"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/elasticsearch_return.py#L208-L331 | train |
saltstack/salt | salt/returners/elasticsearch_return.py | event_return | def event_return(events):
'''
Return events to Elasticsearch
Requires that the `event_return` configuration be set in master config.
'''
options = _get_options()
index = options['master_event_index']
doc_type = options['master_event_doc_type']
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
_ensure_index(index)
for event in events:
data = {
'tag': event.get('tag', ''),
'data': event.get('data', '')
}
ret = __salt__['elasticsearch.document_create'](index=index,
doc_type=doc_type,
id=uuid.uuid4(),
body=salt.utils.json.dumps(data)) | python | def event_return(events):
'''
Return events to Elasticsearch
Requires that the `event_return` configuration be set in master config.
'''
options = _get_options()
index = options['master_event_index']
doc_type = options['master_event_doc_type']
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
_ensure_index(index)
for event in events:
data = {
'tag': event.get('tag', ''),
'data': event.get('data', '')
}
ret = __salt__['elasticsearch.document_create'](index=index,
doc_type=doc_type,
id=uuid.uuid4(),
body=salt.utils.json.dumps(data)) | [
"def",
"event_return",
"(",
"events",
")",
":",
"options",
"=",
"_get_options",
"(",
")",
"index",
"=",
"options",
"[",
"'master_event_index'",
"]",
"doc_type",
"=",
"options",
"[",
"'master_event_doc_type'",
"]",
"if",
"options",
"[",
"'index_date'",
"]",
":"... | Return events to Elasticsearch
Requires that the `event_return` configuration be set in master config. | [
"Return",
"events",
"to",
"Elasticsearch"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/elasticsearch_return.py#L334-L360 | train |
saltstack/salt | salt/returners/elasticsearch_return.py | save_load | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
.. versionadded:: 2015.8.1
'''
options = _get_options()
index = options['master_job_cache_index']
doc_type = options['master_job_cache_doc_type']
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
_ensure_index(index)
# addressing multiple types (bool, string, dict, ...) issue in master_job_cache index for return key (#20826)
if not load.get('return', None) is None:
# if load.return is not a dict, moving the result to load.return.<job_fun_escaped>.return
if not isinstance(load['return'], dict):
job_fun_escaped = load['fun'].replace('.', '_')
load['return'] = {job_fun_escaped: {'return': load['return']}}
# rename load.return to load.data in order to have the same key in all indices (master_job_cache, job)
load['data'] = load.pop('return')
data = {
'jid': jid,
'load': load,
}
ret = __salt__['elasticsearch.document_create'](index=index,
doc_type=doc_type,
id=jid,
body=salt.utils.json.dumps(data)) | python | def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
.. versionadded:: 2015.8.1
'''
options = _get_options()
index = options['master_job_cache_index']
doc_type = options['master_job_cache_doc_type']
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
_ensure_index(index)
# addressing multiple types (bool, string, dict, ...) issue in master_job_cache index for return key (#20826)
if not load.get('return', None) is None:
# if load.return is not a dict, moving the result to load.return.<job_fun_escaped>.return
if not isinstance(load['return'], dict):
job_fun_escaped = load['fun'].replace('.', '_')
load['return'] = {job_fun_escaped: {'return': load['return']}}
# rename load.return to load.data in order to have the same key in all indices (master_job_cache, job)
load['data'] = load.pop('return')
data = {
'jid': jid,
'load': load,
}
ret = __salt__['elasticsearch.document_create'](index=index,
doc_type=doc_type,
id=jid,
body=salt.utils.json.dumps(data)) | [
"def",
"save_load",
"(",
"jid",
",",
"load",
",",
"minions",
"=",
"None",
")",
":",
"options",
"=",
"_get_options",
"(",
")",
"index",
"=",
"options",
"[",
"'master_job_cache_index'",
"]",
"doc_type",
"=",
"options",
"[",
"'master_job_cache_doc_type'",
"]",
... | Save the load to the specified jid id
.. versionadded:: 2015.8.1 | [
"Save",
"the",
"load",
"to",
"the",
"specified",
"jid",
"id"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/elasticsearch_return.py#L370-L404 | train |
saltstack/salt | salt/returners/elasticsearch_return.py | get_load | def get_load(jid):
'''
Return the load data that marks a specified jid
.. versionadded:: 2015.8.1
'''
options = _get_options()
index = options['master_job_cache_index']
doc_type = options['master_job_cache_doc_type']
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
data = __salt__['elasticsearch.document_get'](index=index,
id=jid,
doc_type=doc_type)
if data:
# Use salt.utils.json.dumps to convert elasticsearch unicode json to standard json
return salt.utils.json.loads(salt.utils.json.dumps(data))
return {} | python | def get_load(jid):
'''
Return the load data that marks a specified jid
.. versionadded:: 2015.8.1
'''
options = _get_options()
index = options['master_job_cache_index']
doc_type = options['master_job_cache_doc_type']
if options['index_date']:
index = '{0}-{1}'.format(index,
datetime.date.today().strftime('%Y.%m.%d'))
data = __salt__['elasticsearch.document_get'](index=index,
id=jid,
doc_type=doc_type)
if data:
# Use salt.utils.json.dumps to convert elasticsearch unicode json to standard json
return salt.utils.json.loads(salt.utils.json.dumps(data))
return {} | [
"def",
"get_load",
"(",
"jid",
")",
":",
"options",
"=",
"_get_options",
"(",
")",
"index",
"=",
"options",
"[",
"'master_job_cache_index'",
"]",
"doc_type",
"=",
"options",
"[",
"'master_job_cache_doc_type'",
"]",
"if",
"options",
"[",
"'index_date'",
"]",
":... | Return the load data that marks a specified jid
.. versionadded:: 2015.8.1 | [
"Return",
"the",
"load",
"data",
"that",
"marks",
"a",
"specified",
"jid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/elasticsearch_return.py#L407-L428 | train |
saltstack/salt | salt/runners/manage.py | status | def status(output=True, tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print the status of all known salt minions
CLI Example:
.. code-block:: bash
salt-run manage.status
salt-run manage.status tgt="webservers" tgt_type="nodegroup"
salt-run manage.status timeout=5 gather_job_timeout=10
'''
ret = {}
if not timeout:
timeout = __opts__['timeout']
if not gather_job_timeout:
gather_job_timeout = __opts__['gather_job_timeout']
res = _ping(tgt, tgt_type, timeout, gather_job_timeout)
ret['up'], ret['down'] = ([], []) if not res else res
return ret | python | def status(output=True, tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print the status of all known salt minions
CLI Example:
.. code-block:: bash
salt-run manage.status
salt-run manage.status tgt="webservers" tgt_type="nodegroup"
salt-run manage.status timeout=5 gather_job_timeout=10
'''
ret = {}
if not timeout:
timeout = __opts__['timeout']
if not gather_job_timeout:
gather_job_timeout = __opts__['gather_job_timeout']
res = _ping(tgt, tgt_type, timeout, gather_job_timeout)
ret['up'], ret['down'] = ([], []) if not res else res
return ret | [
"def",
"status",
"(",
"output",
"=",
"True",
",",
"tgt",
"=",
"'*'",
",",
"tgt_type",
"=",
"'glob'",
",",
"timeout",
"=",
"None",
",",
"gather_job_timeout",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"timeout",
":",
"timeout",
"=",
"... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print the status of all known salt minions
CLI Example:
.. code-block:: bash
salt-run manage.status
salt-run manage.status tgt="webservers" tgt_type="nodegroup"
salt-run manage.status timeout=5 gather_job_timeout=10 | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L71-L96 | train |
saltstack/salt | salt/runners/manage.py | key_regen | def key_regen():
'''
This routine is used to regenerate all keys in an environment. This is
invasive! ALL KEYS IN THE SALT ENVIRONMENT WILL BE REGENERATED!!
The key_regen routine sends a command out to minions to revoke the master
key and remove all minion keys, it then removes all keys from the master
and prompts the user to restart the master. The minions will all reconnect
and keys will be placed in pending.
After the master is restarted and minion keys are in the pending directory
execute a salt-key -A command to accept the regenerated minion keys.
The master *must* be restarted within 60 seconds of running this command or
the minions will think there is something wrong with the keys and abort.
Only Execute this runner after upgrading minions and master to 0.15.1 or
higher!
CLI Example:
.. code-block:: bash
salt-run manage.key_regen
'''
client = salt.client.get_local_client(__opts__['conf_file'])
try:
client.cmd('*', 'saltutil.regen_keys')
except SaltClientError as client_error:
print(client_error)
return False
for root, _, files in salt.utils.path.os_walk(__opts__['pki_dir']):
for fn_ in files:
path = os.path.join(root, fn_)
try:
os.remove(path)
except os.error:
pass
msg = ('The minion and master keys have been deleted. Restart the Salt\n'
'Master within the next 60 seconds!!!\n\n'
'Wait for the minions to reconnect. Once the minions reconnect\n'
'the new keys will appear in pending and will need to be re-\n'
'accepted by running:\n'
' salt-key -A\n\n'
'Be advised that minions not currently connected to the master\n'
'will not be able to reconnect and may require manual\n'
'regeneration via a local call to\n'
' salt-call saltutil.regen_keys')
return msg | python | def key_regen():
'''
This routine is used to regenerate all keys in an environment. This is
invasive! ALL KEYS IN THE SALT ENVIRONMENT WILL BE REGENERATED!!
The key_regen routine sends a command out to minions to revoke the master
key and remove all minion keys, it then removes all keys from the master
and prompts the user to restart the master. The minions will all reconnect
and keys will be placed in pending.
After the master is restarted and minion keys are in the pending directory
execute a salt-key -A command to accept the regenerated minion keys.
The master *must* be restarted within 60 seconds of running this command or
the minions will think there is something wrong with the keys and abort.
Only Execute this runner after upgrading minions and master to 0.15.1 or
higher!
CLI Example:
.. code-block:: bash
salt-run manage.key_regen
'''
client = salt.client.get_local_client(__opts__['conf_file'])
try:
client.cmd('*', 'saltutil.regen_keys')
except SaltClientError as client_error:
print(client_error)
return False
for root, _, files in salt.utils.path.os_walk(__opts__['pki_dir']):
for fn_ in files:
path = os.path.join(root, fn_)
try:
os.remove(path)
except os.error:
pass
msg = ('The minion and master keys have been deleted. Restart the Salt\n'
'Master within the next 60 seconds!!!\n\n'
'Wait for the minions to reconnect. Once the minions reconnect\n'
'the new keys will appear in pending and will need to be re-\n'
'accepted by running:\n'
' salt-key -A\n\n'
'Be advised that minions not currently connected to the master\n'
'will not be able to reconnect and may require manual\n'
'regeneration via a local call to\n'
' salt-call saltutil.regen_keys')
return msg | [
"def",
"key_regen",
"(",
")",
":",
"client",
"=",
"salt",
".",
"client",
".",
"get_local_client",
"(",
"__opts__",
"[",
"'conf_file'",
"]",
")",
"try",
":",
"client",
".",
"cmd",
"(",
"'*'",
",",
"'saltutil.regen_keys'",
")",
"except",
"SaltClientError",
"... | This routine is used to regenerate all keys in an environment. This is
invasive! ALL KEYS IN THE SALT ENVIRONMENT WILL BE REGENERATED!!
The key_regen routine sends a command out to minions to revoke the master
key and remove all minion keys, it then removes all keys from the master
and prompts the user to restart the master. The minions will all reconnect
and keys will be placed in pending.
After the master is restarted and minion keys are in the pending directory
execute a salt-key -A command to accept the regenerated minion keys.
The master *must* be restarted within 60 seconds of running this command or
the minions will think there is something wrong with the keys and abort.
Only Execute this runner after upgrading minions and master to 0.15.1 or
higher!
CLI Example:
.. code-block:: bash
salt-run manage.key_regen | [
"This",
"routine",
"is",
"used",
"to",
"regenerate",
"all",
"keys",
"in",
"an",
"environment",
".",
"This",
"is",
"invasive!",
"ALL",
"KEYS",
"IN",
"THE",
"SALT",
"ENVIRONMENT",
"WILL",
"BE",
"REGENERATED!!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L99-L148 | train |
saltstack/salt | salt/runners/manage.py | down | def down(removekeys=False, tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all the down or unresponsive salt minions
Optionally remove keys of down minions
CLI Example:
.. code-block:: bash
salt-run manage.down
salt-run manage.down removekeys=True
salt-run manage.down tgt="webservers" tgt_type="nodegroup"
'''
ret = status(output=False,
tgt=tgt,
tgt_type=tgt_type,
timeout=timeout,
gather_job_timeout=gather_job_timeout
).get('down', [])
for minion in ret:
if removekeys:
wheel = salt.wheel.Wheel(__opts__)
wheel.call_func('key.delete', match=minion)
return ret | python | def down(removekeys=False, tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all the down or unresponsive salt minions
Optionally remove keys of down minions
CLI Example:
.. code-block:: bash
salt-run manage.down
salt-run manage.down removekeys=True
salt-run manage.down tgt="webservers" tgt_type="nodegroup"
'''
ret = status(output=False,
tgt=tgt,
tgt_type=tgt_type,
timeout=timeout,
gather_job_timeout=gather_job_timeout
).get('down', [])
for minion in ret:
if removekeys:
wheel = salt.wheel.Wheel(__opts__)
wheel.call_func('key.delete', match=minion)
return ret | [
"def",
"down",
"(",
"removekeys",
"=",
"False",
",",
"tgt",
"=",
"'*'",
",",
"tgt_type",
"=",
"'glob'",
",",
"timeout",
"=",
"None",
",",
"gather_job_timeout",
"=",
"None",
")",
":",
"ret",
"=",
"status",
"(",
"output",
"=",
"False",
",",
"tgt",
"=",... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all the down or unresponsive salt minions
Optionally remove keys of down minions
CLI Example:
.. code-block:: bash
salt-run manage.down
salt-run manage.down removekeys=True
salt-run manage.down tgt="webservers" tgt_type="nodegroup" | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L151-L179 | train |
saltstack/salt | salt/runners/manage.py | up | def up(tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None): # pylint: disable=C0103
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all of the minions that are up
CLI Example:
.. code-block:: bash
salt-run manage.up
salt-run manage.up tgt="webservers" tgt_type="nodegroup"
salt-run manage.up timeout=5 gather_job_timeout=10
'''
ret = status(
output=False,
tgt=tgt,
tgt_type=tgt_type,
timeout=timeout,
gather_job_timeout=gather_job_timeout
).get('up', [])
return ret | python | def up(tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None): # pylint: disable=C0103
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all of the minions that are up
CLI Example:
.. code-block:: bash
salt-run manage.up
salt-run manage.up tgt="webservers" tgt_type="nodegroup"
salt-run manage.up timeout=5 gather_job_timeout=10
'''
ret = status(
output=False,
tgt=tgt,
tgt_type=tgt_type,
timeout=timeout,
gather_job_timeout=gather_job_timeout
).get('up', [])
return ret | [
"def",
"up",
"(",
"tgt",
"=",
"'*'",
",",
"tgt_type",
"=",
"'glob'",
",",
"timeout",
"=",
"None",
",",
"gather_job_timeout",
"=",
"None",
")",
":",
"# pylint: disable=C0103",
"ret",
"=",
"status",
"(",
"output",
"=",
"False",
",",
"tgt",
"=",
"tgt",
",... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all of the minions that are up
CLI Example:
.. code-block:: bash
salt-run manage.up
salt-run manage.up tgt="webservers" tgt_type="nodegroup"
salt-run manage.up timeout=5 gather_job_timeout=10 | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L182-L205 | train |
saltstack/salt | salt/runners/manage.py | list_state | def list_state(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.list_state
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
# Always return 'present' for 0MQ for now
# TODO: implement other states support for 0MQ
ckminions = salt.utils.minions.CkMinions(__opts__)
minions = ckminions.connected_ids(show_ip=show_ip, subset=subset)
connected = dict(minions) if show_ip else sorted(minions)
return connected | python | def list_state(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.list_state
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
# Always return 'present' for 0MQ for now
# TODO: implement other states support for 0MQ
ckminions = salt.utils.minions.CkMinions(__opts__)
minions = ckminions.connected_ids(show_ip=show_ip, subset=subset)
connected = dict(minions) if show_ip else sorted(minions)
return connected | [
"def",
"list_state",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"# Always return 'present' for 0MQ for now",
"# TODO: implement other... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.list_state | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L220-L251 | train |
saltstack/salt | salt/runners/manage.py | list_not_state | def list_not_state(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.list_not_state
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
connected = list_state(subset=None, show_ip=show_ip)
key = salt.key.get_key(__opts__)
keys = key.list_keys()
not_connected = []
for minion in keys[key.ACC]:
if minion not in connected and (subset is None or minion in subset):
not_connected.append(minion)
return not_connected | python | def list_not_state(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.list_not_state
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
connected = list_state(subset=None, show_ip=show_ip)
key = salt.key.get_key(__opts__)
keys = key.list_keys()
not_connected = []
for minion in keys[key.ACC]:
if minion not in connected and (subset is None or minion in subset):
not_connected.append(minion)
return not_connected | [
"def",
"list_not_state",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"connected",
"=",
"list_state",
"(",
"subset",
"=",
"No... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.list_not_state | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L254-L287 | train |
saltstack/salt | salt/runners/manage.py | present | def present(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.present
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | python | def present(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.present
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | [
"def",
"present",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"... | .. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.present | [
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6",
"-",
"connected",
"minions",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L290-L312 | train |
saltstack/salt | salt/runners/manage.py | not_present | def not_present(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.5.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_present
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | python | def not_present(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.5.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_present
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | [
"def",
"not_present",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_not_state",
"(",
"subset",
"=",
"subset",
... | .. versionadded:: 2015.5.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_present | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L315-L338 | train |
saltstack/salt | salt/runners/manage.py | joined | def joined(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.joined
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | python | def joined(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.joined
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | [
"def",
"joined",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"s... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.joined | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L341-L364 | train |
saltstack/salt | salt/runners/manage.py | not_joined | def not_joined(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_joined
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | python | def not_joined(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_joined
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | [
"def",
"not_joined",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_not_state",
"(",
"subset",
"=",
"subset",
"... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_joined | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L367-L390 | train |
saltstack/salt | salt/runners/manage.py | allowed | def allowed(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.allowed
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | python | def allowed(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.allowed
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | [
"def",
"allowed",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.allowed | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L393-L416 | train |
saltstack/salt | salt/runners/manage.py | not_allowed | def not_allowed(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_allowed
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | python | def not_allowed(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_allowed
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | [
"def",
"not_allowed",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_not_state",
"(",
"subset",
"=",
"subset",
... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_allowed | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L419-L442 | train |
saltstack/salt | salt/runners/manage.py | alived | def alived(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.alived
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | python | def alived(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.alived
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | [
"def",
"alived",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"s... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.alived | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L445-L468 | train |
saltstack/salt | salt/runners/manage.py | not_alived | def not_alived(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_alived
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | python | def not_alived(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_alived
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | [
"def",
"not_alived",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_not_state",
"(",
"subset",
"=",
"subset",
"... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_alived | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L471-L494 | train |
saltstack/salt | salt/runners/manage.py | reaped | def reaped(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.reaped
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | python | def reaped(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.reaped
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_state(subset=subset, show_ip=show_ip) | [
"def",
"reaped",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_state",
"(",
"subset",
"=",
"subset",
",",
"s... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are up according to Salt's presence
detection (no commands will be sent to minions)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.reaped | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L497-L520 | train |
saltstack/salt | salt/runners/manage.py | not_reaped | def not_reaped(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_reaped
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | python | def not_reaped(subset=None, show_ip=False, show_ipv4=None):
'''
.. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_reaped
'''
show_ip = _show_ip_migration(show_ip, show_ipv4)
return list_not_state(subset=subset, show_ip=show_ip) | [
"def",
"not_reaped",
"(",
"subset",
"=",
"None",
",",
"show_ip",
"=",
"False",
",",
"show_ipv4",
"=",
"None",
")",
":",
"show_ip",
"=",
"_show_ip_migration",
"(",
"show_ip",
",",
"show_ipv4",
")",
"return",
"list_not_state",
"(",
"subset",
"=",
"subset",
"... | .. versionadded:: 2015.8.0
.. versionchanged:: 2019.2.0
The 'show_ipv4' argument has been renamed to 'show_ip' as it now
includes IPv6 addresses for IPv6-connected minions.
Print a list of all minions that are NOT up according to Salt's presence
detection (no commands will be sent)
subset : None
Pass in a CIDR range to filter minions by IP address.
show_ip : False
Also show the IP address each minion is connecting from.
CLI Example:
.. code-block:: bash
salt-run manage.not_reaped | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"0",
"..",
"versionchanged",
"::",
"2019",
".",
"2",
".",
"0",
"The",
"show_ipv4",
"argument",
"has",
"been",
"renamed",
"to",
"show_ip",
"as",
"it",
"now",
"includes",
"IPv6",
"addresses",
"for",
"IPv6"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L523-L546 | train |
saltstack/salt | salt/runners/manage.py | safe_accept | def safe_accept(target, tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Accept a minion's public key after checking the fingerprint over salt-ssh
CLI Example:
.. code-block:: bash
salt-run manage.safe_accept my_minion
salt-run manage.safe_accept minion1,minion2 tgt_type=list
'''
salt_key = salt.key.Key(__opts__)
ssh_client = salt.client.ssh.client.SSHClient()
ret = ssh_client.cmd(target, 'key.finger', tgt_type=tgt_type)
failures = {}
for minion, finger in six.iteritems(ret):
if not FINGERPRINT_REGEX.match(finger):
failures[minion] = finger
else:
fingerprints = salt_key.finger(minion)
accepted = fingerprints.get('minions', {})
pending = fingerprints.get('minions_pre', {})
if minion in accepted:
del ret[minion]
continue
elif minion not in pending:
failures[minion] = ("Minion key {0} not found by salt-key"
.format(minion))
elif pending[minion] != finger:
failures[minion] = ("Minion key {0} does not match the key in "
"salt-key: {1}"
.format(finger, pending[minion]))
else:
subprocess.call(["salt-key", "-qya", minion])
if minion in failures:
del ret[minion]
if failures:
print('safe_accept failed on the following minions:')
for minion, message in six.iteritems(failures):
print(minion)
print('-' * len(minion))
print(message)
print('')
__jid_event__.fire_event({'message': 'Accepted {0:d} keys'.format(len(ret))}, 'progress')
return ret, failures | python | def safe_accept(target, tgt_type='glob'):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Accept a minion's public key after checking the fingerprint over salt-ssh
CLI Example:
.. code-block:: bash
salt-run manage.safe_accept my_minion
salt-run manage.safe_accept minion1,minion2 tgt_type=list
'''
salt_key = salt.key.Key(__opts__)
ssh_client = salt.client.ssh.client.SSHClient()
ret = ssh_client.cmd(target, 'key.finger', tgt_type=tgt_type)
failures = {}
for minion, finger in six.iteritems(ret):
if not FINGERPRINT_REGEX.match(finger):
failures[minion] = finger
else:
fingerprints = salt_key.finger(minion)
accepted = fingerprints.get('minions', {})
pending = fingerprints.get('minions_pre', {})
if minion in accepted:
del ret[minion]
continue
elif minion not in pending:
failures[minion] = ("Minion key {0} not found by salt-key"
.format(minion))
elif pending[minion] != finger:
failures[minion] = ("Minion key {0} does not match the key in "
"salt-key: {1}"
.format(finger, pending[minion]))
else:
subprocess.call(["salt-key", "-qya", minion])
if minion in failures:
del ret[minion]
if failures:
print('safe_accept failed on the following minions:')
for minion, message in six.iteritems(failures):
print(minion)
print('-' * len(minion))
print(message)
print('')
__jid_event__.fire_event({'message': 'Accepted {0:d} keys'.format(len(ret))}, 'progress')
return ret, failures | [
"def",
"safe_accept",
"(",
"target",
",",
"tgt_type",
"=",
"'glob'",
")",
":",
"salt_key",
"=",
"salt",
".",
"key",
".",
"Key",
"(",
"__opts__",
")",
"ssh_client",
"=",
"salt",
".",
"client",
".",
"ssh",
".",
"client",
".",
"SSHClient",
"(",
")",
"re... | .. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Accept a minion's public key after checking the fingerprint over salt-ssh
CLI Example:
.. code-block:: bash
salt-run manage.safe_accept my_minion
salt-run manage.safe_accept minion1,minion2 tgt_type=list | [
"..",
"versionchanged",
"::",
"2017",
".",
"7",
".",
"0",
"The",
"expr_form",
"argument",
"has",
"been",
"renamed",
"to",
"tgt_type",
"earlier",
"releases",
"must",
"use",
"expr_form",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L549-L602 | train |
saltstack/salt | salt/runners/manage.py | versions | def versions():
'''
Check the version of active minions
CLI Example:
.. code-block:: bash
salt-run manage.versions
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
minions = client.cmd('*', 'test.version', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
labels = {
-2: 'Minion offline',
-1: 'Minion requires update',
0: 'Up to date',
1: 'Minion newer than master',
2: 'Master',
}
version_status = {}
master_version = salt.version.__saltstack_version__
for minion in minions:
if not minions[minion]:
minion_version = False
ver_diff = -2
else:
minion_version = salt.version.SaltStackVersion.parse(minions[minion])
ver_diff = salt.utils.compat.cmp(minion_version, master_version)
if ver_diff not in version_status:
version_status[ver_diff] = {}
if minion_version:
version_status[ver_diff][minion] = minion_version.string
else:
version_status[ver_diff][minion] = minion_version
# Add version of Master to output
version_status[2] = master_version.string
for key in version_status:
if key == 2:
ret[labels[key]] = version_status[2]
else:
for minion in sorted(version_status[key]):
ret.setdefault(labels[key], {})[minion] = version_status[key][minion]
return ret | python | def versions():
'''
Check the version of active minions
CLI Example:
.. code-block:: bash
salt-run manage.versions
'''
ret = {}
client = salt.client.get_local_client(__opts__['conf_file'])
try:
minions = client.cmd('*', 'test.version', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
labels = {
-2: 'Minion offline',
-1: 'Minion requires update',
0: 'Up to date',
1: 'Minion newer than master',
2: 'Master',
}
version_status = {}
master_version = salt.version.__saltstack_version__
for minion in minions:
if not minions[minion]:
minion_version = False
ver_diff = -2
else:
minion_version = salt.version.SaltStackVersion.parse(minions[minion])
ver_diff = salt.utils.compat.cmp(minion_version, master_version)
if ver_diff not in version_status:
version_status[ver_diff] = {}
if minion_version:
version_status[ver_diff][minion] = minion_version.string
else:
version_status[ver_diff][minion] = minion_version
# Add version of Master to output
version_status[2] = master_version.string
for key in version_status:
if key == 2:
ret[labels[key]] = version_status[2]
else:
for minion in sorted(version_status[key]):
ret.setdefault(labels[key], {})[minion] = version_status[key][minion]
return ret | [
"def",
"versions",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"client",
"=",
"salt",
".",
"client",
".",
"get_local_client",
"(",
"__opts__",
"[",
"'conf_file'",
"]",
")",
"try",
":",
"minions",
"=",
"client",
".",
"cmd",
"(",
"'*'",
",",
"'test.version'",
... | Check the version of active minions
CLI Example:
.. code-block:: bash
salt-run manage.versions | [
"Check",
"the",
"version",
"of",
"active",
"minions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L605-L659 | train |
saltstack/salt | salt/runners/manage.py | bootstrap | def bootstrap(version='develop',
script=None,
hosts='',
script_args='',
roster='flat',
ssh_user=None,
ssh_password=None,
ssh_priv_key=None,
tmp_dir='/tmp/.bootstrap',
http_backend='tornado'):
'''
Bootstrap minions with salt-bootstrap
version : develop
Git tag of version to install
script : https://bootstrap.saltstack.com
URL containing the script to execute
hosts
Comma-separated hosts [example: hosts='host1.local,host2.local']. These
hosts need to exist in the specified roster.
script_args
Any additional arguments that you want to pass to the script.
.. versionadded:: 2016.11.0
roster : flat
The roster to use for Salt SSH. More information about roster files can
be found in :ref:`Salt's Roster Documentation <ssh-roster>`.
A full list of roster types, see the :ref:`builtin roster modules <all-salt.roster>`
documentation.
.. versionadded:: 2016.11.0
ssh_user
If ``user`` isn't found in the ``roster``, a default SSH user can be set here.
Keep in mind that ``ssh_user`` will not override the roster ``user`` value if
it is already defined.
.. versionadded:: 2016.11.0
ssh_password
If ``passwd`` isn't found in the ``roster``, a default SSH password can be set
here. Keep in mind that ``ssh_password`` will not override the roster ``passwd``
value if it is already defined.
.. versionadded:: 2016.11.0
ssh_privkey
If ``priv`` isn't found in the ``roster``, a default SSH private key can be set
here. Keep in mind that ``ssh_password`` will not override the roster ``passwd``
value if it is already defined.
.. versionadded:: 2016.11.0
tmp_dir : /tmp/.bootstrap
The temporary directory to download the bootstrap script in. This
directory will have ``-<uuid4>`` appended to it. For example:
``/tmp/.bootstrap-a19a728e-d40a-4801-aba9-d00655c143a7/``
.. versionadded:: 2016.11.0
http_backend : tornado
The backend library to use to download the script. If you need to use
a ``file:///`` URL, then you should set this to ``urllib2``.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt-run manage.bootstrap hosts='host1,host2'
salt-run manage.bootstrap hosts='host1,host2' version='v0.17'
salt-run manage.bootstrap hosts='host1,host2' version='v0.17' \
script='https://bootstrap.saltstack.com/develop'
'''
if script is None:
script = 'https://bootstrap.saltstack.com'
client_opts = __opts__.copy()
if roster is not None:
client_opts['roster'] = roster
if ssh_user is not None:
client_opts['ssh_user'] = ssh_user
if ssh_password is not None:
client_opts['ssh_passwd'] = ssh_password
if ssh_priv_key is not None:
client_opts['ssh_priv'] = ssh_priv_key
for host in hosts.split(','):
client_opts['tgt'] = host
client_opts['selected_target_option'] = 'glob'
tmp_dir = '{0}-{1}/'.format(tmp_dir.rstrip('/'), uuid.uuid4())
deploy_command = os.path.join(tmp_dir, 'deploy.sh')
try:
client_opts['argv'] = ['file.makedirs', tmp_dir, 'mode=0700']
salt.client.ssh.SSH(client_opts).run()
client_opts['argv'] = [
'http.query',
script,
'backend={0}'.format(http_backend),
'text_out={0}'.format(deploy_command)
]
client = salt.client.ssh.SSH(client_opts).run()
client_opts['argv'] = [
'cmd.run',
' '.join(['sh', deploy_command, script_args]),
'python_shell=False'
]
salt.client.ssh.SSH(client_opts).run()
client_opts['argv'] = ['file.remove', tmp_dir]
salt.client.ssh.SSH(client_opts).run()
except SaltSystemExit as exc:
log.error(six.text_type(exc)) | python | def bootstrap(version='develop',
script=None,
hosts='',
script_args='',
roster='flat',
ssh_user=None,
ssh_password=None,
ssh_priv_key=None,
tmp_dir='/tmp/.bootstrap',
http_backend='tornado'):
'''
Bootstrap minions with salt-bootstrap
version : develop
Git tag of version to install
script : https://bootstrap.saltstack.com
URL containing the script to execute
hosts
Comma-separated hosts [example: hosts='host1.local,host2.local']. These
hosts need to exist in the specified roster.
script_args
Any additional arguments that you want to pass to the script.
.. versionadded:: 2016.11.0
roster : flat
The roster to use for Salt SSH. More information about roster files can
be found in :ref:`Salt's Roster Documentation <ssh-roster>`.
A full list of roster types, see the :ref:`builtin roster modules <all-salt.roster>`
documentation.
.. versionadded:: 2016.11.0
ssh_user
If ``user`` isn't found in the ``roster``, a default SSH user can be set here.
Keep in mind that ``ssh_user`` will not override the roster ``user`` value if
it is already defined.
.. versionadded:: 2016.11.0
ssh_password
If ``passwd`` isn't found in the ``roster``, a default SSH password can be set
here. Keep in mind that ``ssh_password`` will not override the roster ``passwd``
value if it is already defined.
.. versionadded:: 2016.11.0
ssh_privkey
If ``priv`` isn't found in the ``roster``, a default SSH private key can be set
here. Keep in mind that ``ssh_password`` will not override the roster ``passwd``
value if it is already defined.
.. versionadded:: 2016.11.0
tmp_dir : /tmp/.bootstrap
The temporary directory to download the bootstrap script in. This
directory will have ``-<uuid4>`` appended to it. For example:
``/tmp/.bootstrap-a19a728e-d40a-4801-aba9-d00655c143a7/``
.. versionadded:: 2016.11.0
http_backend : tornado
The backend library to use to download the script. If you need to use
a ``file:///`` URL, then you should set this to ``urllib2``.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt-run manage.bootstrap hosts='host1,host2'
salt-run manage.bootstrap hosts='host1,host2' version='v0.17'
salt-run manage.bootstrap hosts='host1,host2' version='v0.17' \
script='https://bootstrap.saltstack.com/develop'
'''
if script is None:
script = 'https://bootstrap.saltstack.com'
client_opts = __opts__.copy()
if roster is not None:
client_opts['roster'] = roster
if ssh_user is not None:
client_opts['ssh_user'] = ssh_user
if ssh_password is not None:
client_opts['ssh_passwd'] = ssh_password
if ssh_priv_key is not None:
client_opts['ssh_priv'] = ssh_priv_key
for host in hosts.split(','):
client_opts['tgt'] = host
client_opts['selected_target_option'] = 'glob'
tmp_dir = '{0}-{1}/'.format(tmp_dir.rstrip('/'), uuid.uuid4())
deploy_command = os.path.join(tmp_dir, 'deploy.sh')
try:
client_opts['argv'] = ['file.makedirs', tmp_dir, 'mode=0700']
salt.client.ssh.SSH(client_opts).run()
client_opts['argv'] = [
'http.query',
script,
'backend={0}'.format(http_backend),
'text_out={0}'.format(deploy_command)
]
client = salt.client.ssh.SSH(client_opts).run()
client_opts['argv'] = [
'cmd.run',
' '.join(['sh', deploy_command, script_args]),
'python_shell=False'
]
salt.client.ssh.SSH(client_opts).run()
client_opts['argv'] = ['file.remove', tmp_dir]
salt.client.ssh.SSH(client_opts).run()
except SaltSystemExit as exc:
log.error(six.text_type(exc)) | [
"def",
"bootstrap",
"(",
"version",
"=",
"'develop'",
",",
"script",
"=",
"None",
",",
"hosts",
"=",
"''",
",",
"script_args",
"=",
"''",
",",
"roster",
"=",
"'flat'",
",",
"ssh_user",
"=",
"None",
",",
"ssh_password",
"=",
"None",
",",
"ssh_priv_key",
... | Bootstrap minions with salt-bootstrap
version : develop
Git tag of version to install
script : https://bootstrap.saltstack.com
URL containing the script to execute
hosts
Comma-separated hosts [example: hosts='host1.local,host2.local']. These
hosts need to exist in the specified roster.
script_args
Any additional arguments that you want to pass to the script.
.. versionadded:: 2016.11.0
roster : flat
The roster to use for Salt SSH. More information about roster files can
be found in :ref:`Salt's Roster Documentation <ssh-roster>`.
A full list of roster types, see the :ref:`builtin roster modules <all-salt.roster>`
documentation.
.. versionadded:: 2016.11.0
ssh_user
If ``user`` isn't found in the ``roster``, a default SSH user can be set here.
Keep in mind that ``ssh_user`` will not override the roster ``user`` value if
it is already defined.
.. versionadded:: 2016.11.0
ssh_password
If ``passwd`` isn't found in the ``roster``, a default SSH password can be set
here. Keep in mind that ``ssh_password`` will not override the roster ``passwd``
value if it is already defined.
.. versionadded:: 2016.11.0
ssh_privkey
If ``priv`` isn't found in the ``roster``, a default SSH private key can be set
here. Keep in mind that ``ssh_password`` will not override the roster ``passwd``
value if it is already defined.
.. versionadded:: 2016.11.0
tmp_dir : /tmp/.bootstrap
The temporary directory to download the bootstrap script in. This
directory will have ``-<uuid4>`` appended to it. For example:
``/tmp/.bootstrap-a19a728e-d40a-4801-aba9-d00655c143a7/``
.. versionadded:: 2016.11.0
http_backend : tornado
The backend library to use to download the script. If you need to use
a ``file:///`` URL, then you should set this to ``urllib2``.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt-run manage.bootstrap hosts='host1,host2'
salt-run manage.bootstrap hosts='host1,host2' version='v0.17'
salt-run manage.bootstrap hosts='host1,host2' version='v0.17' \
script='https://bootstrap.saltstack.com/develop' | [
"Bootstrap",
"minions",
"with",
"salt",
"-",
"bootstrap"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L662-L784 | train |
saltstack/salt | salt/runners/manage.py | bootstrap_psexec | def bootstrap_psexec(hosts='', master=None, version=None, arch='win32',
installer_url=None, username=None, password=None):
'''
Bootstrap Windows minions via PsExec.
hosts
Comma separated list of hosts to deploy the Windows Salt minion.
master
Address of the Salt master passed as an argument to the installer.
version
Point release of installer to download. Defaults to the most recent.
arch
Architecture of installer to download. Defaults to win32.
installer_url
URL of minion installer executable. Defaults to the latest version from
https://repo.saltstack.com/windows/
username
Optional user name for login on remote computer.
password
Password for optional username. If omitted, PsExec will prompt for one
to be entered for each host.
CLI Example:
.. code-block:: bash
salt-run manage.bootstrap_psexec hosts='host1,host2'
salt-run manage.bootstrap_psexec hosts='host1,host2' version='0.17' username='DOMAIN\\Administrator'
salt-run manage.bootstrap_psexec hosts='host1,host2' installer_url='http://exampledomain/salt-installer.exe'
'''
if not installer_url:
base_url = 'https://repo.saltstack.com/windows/'
source = _urlopen(base_url).read()
salty_rx = re.compile('>(Salt-Minion-(.+?)-(.+)-Setup.exe)</a></td><td align="right">(.*?)\\s*<')
source_list = sorted([[path, ver, plat, time.strptime(date, "%d-%b-%Y %H:%M")]
for path, ver, plat, date in salty_rx.findall(source)],
key=operator.itemgetter(3), reverse=True)
if version:
source_list = [s for s in source_list if s[1] == version]
if arch:
source_list = [s for s in source_list if s[2] == arch]
if not source_list:
return -1
version = source_list[0][1]
arch = source_list[0][2]
installer_url = base_url + source_list[0][0]
# It's no secret that Windows is notoriously command-line hostile.
# Win 7 and newer can use PowerShell out of the box, but to reach
# all those XP and 2K3 machines we must suppress our gag-reflex
# and use VB!
# The following script was borrowed from an informative article about
# downloading exploit payloads for malware. Nope, no irony here.
# http://www.greyhathacker.net/?p=500
vb_script = '''strFileURL = "{0}"
strHDLocation = "{1}"
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing
Set objShell = CreateObject("WScript.Shell")
objShell.Exec("{1}{2}")'''
vb_saltexec = 'saltinstall.exe'
vb_saltexec_args = ' /S /minion-name=%COMPUTERNAME%'
if master:
vb_saltexec_args += ' /master={0}'.format(master)
# One further thing we need to do; the Windows Salt minion is pretty
# self-contained, except for the Microsoft Visual C++ 2008 runtime.
# It's tiny, so the bootstrap will attempt a silent install.
vb_vcrunexec = 'vcredist.exe'
if arch == 'AMD64':
vb_vcrun = vb_script.format(
'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe',
vb_vcrunexec,
' /q')
else:
vb_vcrun = vb_script.format(
'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-795376989c03/vcredist_x86.exe',
vb_vcrunexec,
' /q')
vb_salt = vb_script.format(installer_url, vb_saltexec, vb_saltexec_args)
# PsExec doesn't like extra long arguments; save the instructions as a batch
# file so we can fire it over for execution.
# First off, change to the local temp directory, stop salt-minion (if
# running), and remove the master's public key.
# This is to accommodate for reinstalling Salt over an old or broken build,
# e.g. if the master address is changed, the salt-minion process will fail
# to authenticate and quit; which means infinite restarts under Windows.
batch = 'cd /d %TEMP%\nnet stop salt-minion\ndel c:\\salt\\conf\\pki\\minion\\minion_master.pub\n'
# Speaking of command-line hostile, cscript only supports reading a script
# from a file. Glue it together line by line.
for x, y in ((vb_vcrunexec, vb_vcrun), (vb_saltexec, vb_salt)):
vb_lines = y.split('\n')
batch += '\ndel ' + x + '\n@echo ' + vb_lines[0] + ' >' + \
x + '.vbs\n@echo ' + \
(' >>' + x + '.vbs\n@echo ').join(vb_lines[1:]) + \
' >>' + x + '.vbs\ncscript.exe /NoLogo ' + x + '.vbs'
batch_path = tempfile.mkstemp(suffix='.bat')[1]
with salt.utils.files.fopen(batch_path, 'wb') as batch_file:
batch_file.write(batch)
for host in hosts.split(","):
argv = ['psexec', '\\\\' + host]
if username:
argv += ['-u', username]
if password:
argv += ['-p', password]
argv += ['-h', '-c', batch_path]
subprocess.call(argv) | python | def bootstrap_psexec(hosts='', master=None, version=None, arch='win32',
installer_url=None, username=None, password=None):
'''
Bootstrap Windows minions via PsExec.
hosts
Comma separated list of hosts to deploy the Windows Salt minion.
master
Address of the Salt master passed as an argument to the installer.
version
Point release of installer to download. Defaults to the most recent.
arch
Architecture of installer to download. Defaults to win32.
installer_url
URL of minion installer executable. Defaults to the latest version from
https://repo.saltstack.com/windows/
username
Optional user name for login on remote computer.
password
Password for optional username. If omitted, PsExec will prompt for one
to be entered for each host.
CLI Example:
.. code-block:: bash
salt-run manage.bootstrap_psexec hosts='host1,host2'
salt-run manage.bootstrap_psexec hosts='host1,host2' version='0.17' username='DOMAIN\\Administrator'
salt-run manage.bootstrap_psexec hosts='host1,host2' installer_url='http://exampledomain/salt-installer.exe'
'''
if not installer_url:
base_url = 'https://repo.saltstack.com/windows/'
source = _urlopen(base_url).read()
salty_rx = re.compile('>(Salt-Minion-(.+?)-(.+)-Setup.exe)</a></td><td align="right">(.*?)\\s*<')
source_list = sorted([[path, ver, plat, time.strptime(date, "%d-%b-%Y %H:%M")]
for path, ver, plat, date in salty_rx.findall(source)],
key=operator.itemgetter(3), reverse=True)
if version:
source_list = [s for s in source_list if s[1] == version]
if arch:
source_list = [s for s in source_list if s[2] == arch]
if not source_list:
return -1
version = source_list[0][1]
arch = source_list[0][2]
installer_url = base_url + source_list[0][0]
# It's no secret that Windows is notoriously command-line hostile.
# Win 7 and newer can use PowerShell out of the box, but to reach
# all those XP and 2K3 machines we must suppress our gag-reflex
# and use VB!
# The following script was borrowed from an informative article about
# downloading exploit payloads for malware. Nope, no irony here.
# http://www.greyhathacker.net/?p=500
vb_script = '''strFileURL = "{0}"
strHDLocation = "{1}"
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing
Set objShell = CreateObject("WScript.Shell")
objShell.Exec("{1}{2}")'''
vb_saltexec = 'saltinstall.exe'
vb_saltexec_args = ' /S /minion-name=%COMPUTERNAME%'
if master:
vb_saltexec_args += ' /master={0}'.format(master)
# One further thing we need to do; the Windows Salt minion is pretty
# self-contained, except for the Microsoft Visual C++ 2008 runtime.
# It's tiny, so the bootstrap will attempt a silent install.
vb_vcrunexec = 'vcredist.exe'
if arch == 'AMD64':
vb_vcrun = vb_script.format(
'http://download.microsoft.com/download/d/2/4/d242c3fb-da5a-4542-ad66-f9661d0a8d19/vcredist_x64.exe',
vb_vcrunexec,
' /q')
else:
vb_vcrun = vb_script.format(
'http://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-795376989c03/vcredist_x86.exe',
vb_vcrunexec,
' /q')
vb_salt = vb_script.format(installer_url, vb_saltexec, vb_saltexec_args)
# PsExec doesn't like extra long arguments; save the instructions as a batch
# file so we can fire it over for execution.
# First off, change to the local temp directory, stop salt-minion (if
# running), and remove the master's public key.
# This is to accommodate for reinstalling Salt over an old or broken build,
# e.g. if the master address is changed, the salt-minion process will fail
# to authenticate and quit; which means infinite restarts under Windows.
batch = 'cd /d %TEMP%\nnet stop salt-minion\ndel c:\\salt\\conf\\pki\\minion\\minion_master.pub\n'
# Speaking of command-line hostile, cscript only supports reading a script
# from a file. Glue it together line by line.
for x, y in ((vb_vcrunexec, vb_vcrun), (vb_saltexec, vb_salt)):
vb_lines = y.split('\n')
batch += '\ndel ' + x + '\n@echo ' + vb_lines[0] + ' >' + \
x + '.vbs\n@echo ' + \
(' >>' + x + '.vbs\n@echo ').join(vb_lines[1:]) + \
' >>' + x + '.vbs\ncscript.exe /NoLogo ' + x + '.vbs'
batch_path = tempfile.mkstemp(suffix='.bat')[1]
with salt.utils.files.fopen(batch_path, 'wb') as batch_file:
batch_file.write(batch)
for host in hosts.split(","):
argv = ['psexec', '\\\\' + host]
if username:
argv += ['-u', username]
if password:
argv += ['-p', password]
argv += ['-h', '-c', batch_path]
subprocess.call(argv) | [
"def",
"bootstrap_psexec",
"(",
"hosts",
"=",
"''",
",",
"master",
"=",
"None",
",",
"version",
"=",
"None",
",",
"arch",
"=",
"'win32'",
",",
"installer_url",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"... | Bootstrap Windows minions via PsExec.
hosts
Comma separated list of hosts to deploy the Windows Salt minion.
master
Address of the Salt master passed as an argument to the installer.
version
Point release of installer to download. Defaults to the most recent.
arch
Architecture of installer to download. Defaults to win32.
installer_url
URL of minion installer executable. Defaults to the latest version from
https://repo.saltstack.com/windows/
username
Optional user name for login on remote computer.
password
Password for optional username. If omitted, PsExec will prompt for one
to be entered for each host.
CLI Example:
.. code-block:: bash
salt-run manage.bootstrap_psexec hosts='host1,host2'
salt-run manage.bootstrap_psexec hosts='host1,host2' version='0.17' username='DOMAIN\\Administrator'
salt-run manage.bootstrap_psexec hosts='host1,host2' installer_url='http://exampledomain/salt-installer.exe' | [
"Bootstrap",
"Windows",
"minions",
"via",
"PsExec",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/manage.py#L787-L922 | train |
saltstack/salt | salt/modules/launchctl_service.py | _available_services | def _available_services():
'''
Return a dictionary of all available services on the system
'''
available_services = dict()
for launch_dir in _launchd_paths():
for root, dirs, files in salt.utils.path.os_walk(launch_dir):
for filename in files:
file_path = os.path.join(root, filename)
# Follow symbolic links of files in _launchd_paths
true_path = os.path.realpath(file_path)
# ignore broken symlinks
if not os.path.exists(true_path):
continue
try:
# This assumes most of the plist files
# will be already in XML format
with salt.utils.files.fopen(file_path):
plist = plistlib.readPlist(
salt.utils.data.decode(true_path)
)
except Exception:
# If plistlib is unable to read the file we'll need to use
# the system provided plutil program to do the conversion
cmd = '/usr/bin/plutil -convert xml1 -o - -- "{0}"'.format(
true_path)
plist_xml = __salt__['cmd.run_all'](
cmd, python_shell=False)['stdout']
if six.PY2:
plist = plistlib.readPlistFromString(plist_xml)
else:
plist = plistlib.readPlistFromBytes(
salt.utils.stringutils.to_bytes(plist_xml))
try:
available_services[plist.Label.lower()] = {
'filename': filename,
'file_path': true_path,
'plist': plist,
}
except AttributeError:
# As of MacOS 10.12 there might be plist files without Label key
# in the searched directories. As these files do not represent
# services, thay are not added to the list.
pass
return available_services | python | def _available_services():
'''
Return a dictionary of all available services on the system
'''
available_services = dict()
for launch_dir in _launchd_paths():
for root, dirs, files in salt.utils.path.os_walk(launch_dir):
for filename in files:
file_path = os.path.join(root, filename)
# Follow symbolic links of files in _launchd_paths
true_path = os.path.realpath(file_path)
# ignore broken symlinks
if not os.path.exists(true_path):
continue
try:
# This assumes most of the plist files
# will be already in XML format
with salt.utils.files.fopen(file_path):
plist = plistlib.readPlist(
salt.utils.data.decode(true_path)
)
except Exception:
# If plistlib is unable to read the file we'll need to use
# the system provided plutil program to do the conversion
cmd = '/usr/bin/plutil -convert xml1 -o - -- "{0}"'.format(
true_path)
plist_xml = __salt__['cmd.run_all'](
cmd, python_shell=False)['stdout']
if six.PY2:
plist = plistlib.readPlistFromString(plist_xml)
else:
plist = plistlib.readPlistFromBytes(
salt.utils.stringutils.to_bytes(plist_xml))
try:
available_services[plist.Label.lower()] = {
'filename': filename,
'file_path': true_path,
'plist': plist,
}
except AttributeError:
# As of MacOS 10.12 there might be plist files without Label key
# in the searched directories. As these files do not represent
# services, thay are not added to the list.
pass
return available_services | [
"def",
"_available_services",
"(",
")",
":",
"available_services",
"=",
"dict",
"(",
")",
"for",
"launch_dir",
"in",
"_launchd_paths",
"(",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"salt",
".",
"utils",
".",
"path",
".",
"os_walk",
"(",
... | Return a dictionary of all available services on the system | [
"Return",
"a",
"dictionary",
"of",
"all",
"available",
"services",
"on",
"the",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L77-L125 | train |
saltstack/salt | salt/modules/launchctl_service.py | _service_by_name | def _service_by_name(name):
'''
Return the service info for a service by label, filename or path
'''
services = _available_services()
name = name.lower()
if name in services:
# Match on label
return services[name]
for service in six.itervalues(services):
if service['file_path'].lower() == name:
# Match on full path
return service
basename, ext = os.path.splitext(service['filename'])
if basename.lower() == name:
# Match on basename
return service
return False | python | def _service_by_name(name):
'''
Return the service info for a service by label, filename or path
'''
services = _available_services()
name = name.lower()
if name in services:
# Match on label
return services[name]
for service in six.itervalues(services):
if service['file_path'].lower() == name:
# Match on full path
return service
basename, ext = os.path.splitext(service['filename'])
if basename.lower() == name:
# Match on basename
return service
return False | [
"def",
"_service_by_name",
"(",
"name",
")",
":",
"services",
"=",
"_available_services",
"(",
")",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"if",
"name",
"in",
"services",
":",
"# Match on label",
"return",
"services",
"[",
"name",
"]",
"for",
"servic... | Return the service info for a service by label, filename or path | [
"Return",
"the",
"service",
"info",
"for",
"a",
"service",
"by",
"label",
"filename",
"or",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/launchctl_service.py#L128-L148 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.