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/states/win_system.py | workgroup | def workgroup(name):
'''
.. versionadded:: 2019.2.0
Manage the workgroup of the computer
name
The workgroup to set
Example:
.. code-block:: yaml
set workgroup:
system.workgroup:
- name: local
'''
ret = {'name': name.upper(), 'result': False, 'changes': {}, 'comment': ''}
# Grab the current domain/workgroup
out = __salt__['system.get_domain_workgroup']()
current_workgroup = out['Domain'] if 'Domain' in out else out['Workgroup'] if 'Workgroup' in out else ''
# Notify the user if the requested workgroup is the same
if current_workgroup.upper() == name.upper():
ret['result'] = True
ret['comment'] = "Workgroup is already set to '{0}'".format(name.upper())
return ret
# If being run in test-mode, inform the user what is supposed to happen
if __opts__['test']:
ret['result'] = None
ret['changes'] = {}
ret['comment'] = 'Computer will be joined to workgroup \'{0}\''.format(name)
return ret
# Set our new workgroup, and then immediately ask the machine what it
# is again to validate the change
res = __salt__['system.set_domain_workgroup'](name.upper())
out = __salt__['system.get_domain_workgroup']()
changed_workgroup = out['Domain'] if 'Domain' in out else out['Workgroup'] if 'Workgroup' in out else ''
# Return our results based on the changes
ret = {}
if res and current_workgroup.upper() == changed_workgroup.upper():
ret['result'] = True
ret['comment'] = "The new workgroup '{0}' is the same as '{1}'".format(current_workgroup.upper(), changed_workgroup.upper())
elif res:
ret['result'] = True
ret['comment'] = "The workgroup has been changed from '{0}' to '{1}'".format(current_workgroup.upper(), changed_workgroup.upper())
ret['changes'] = {'old': current_workgroup.upper(), 'new': changed_workgroup.upper()}
else:
ret['result'] = False
ret['comment'] = "Unable to join the requested workgroup '{0}'".format(changed_workgroup.upper())
return ret | python | def workgroup(name):
'''
.. versionadded:: 2019.2.0
Manage the workgroup of the computer
name
The workgroup to set
Example:
.. code-block:: yaml
set workgroup:
system.workgroup:
- name: local
'''
ret = {'name': name.upper(), 'result': False, 'changes': {}, 'comment': ''}
# Grab the current domain/workgroup
out = __salt__['system.get_domain_workgroup']()
current_workgroup = out['Domain'] if 'Domain' in out else out['Workgroup'] if 'Workgroup' in out else ''
# Notify the user if the requested workgroup is the same
if current_workgroup.upper() == name.upper():
ret['result'] = True
ret['comment'] = "Workgroup is already set to '{0}'".format(name.upper())
return ret
# If being run in test-mode, inform the user what is supposed to happen
if __opts__['test']:
ret['result'] = None
ret['changes'] = {}
ret['comment'] = 'Computer will be joined to workgroup \'{0}\''.format(name)
return ret
# Set our new workgroup, and then immediately ask the machine what it
# is again to validate the change
res = __salt__['system.set_domain_workgroup'](name.upper())
out = __salt__['system.get_domain_workgroup']()
changed_workgroup = out['Domain'] if 'Domain' in out else out['Workgroup'] if 'Workgroup' in out else ''
# Return our results based on the changes
ret = {}
if res and current_workgroup.upper() == changed_workgroup.upper():
ret['result'] = True
ret['comment'] = "The new workgroup '{0}' is the same as '{1}'".format(current_workgroup.upper(), changed_workgroup.upper())
elif res:
ret['result'] = True
ret['comment'] = "The workgroup has been changed from '{0}' to '{1}'".format(current_workgroup.upper(), changed_workgroup.upper())
ret['changes'] = {'old': current_workgroup.upper(), 'new': changed_workgroup.upper()}
else:
ret['result'] = False
ret['comment'] = "Unable to join the requested workgroup '{0}'".format(changed_workgroup.upper())
return ret | [
"def",
"workgroup",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
".",
"upper",
"(",
")",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"# Grab the current domain/workgroup",
"out",
"... | .. versionadded:: 2019.2.0
Manage the workgroup of the computer
name
The workgroup to set
Example:
.. code-block:: yaml
set workgroup:
system.workgroup:
- name: local | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L170-L225 | train |
saltstack/salt | salt/states/win_system.py | join_domain | def join_domain(name,
username=None,
password=None,
account_ou=None,
account_exists=False,
restart=False):
'''
Checks if a computer is joined to the Domain. If the computer is not in the
Domain, it will be joined.
Args:
name (str):
The name of the Domain.
username (str):
Username of an account which is authorized to join computers to the
specified domain. Need to be either fully qualified like
user@domain.tld or simply user.
password (str):
Password of the account to add the computer to the Domain.
account_ou (str):
The DN of the OU below which the account for this computer should be
created when joining the domain,
e.g. ou=computers,ou=departm_432,dc=my-company,dc=com.
account_exists (bool):
Needs to be set to ``True`` to allow re-using an existing computer
account.
restart (bool):
Needs to be set to ``True`` to restart the computer after a
successful join.
Example:
.. code-block:: yaml
join_to_domain:
system.join_domain:
- name: mydomain.local.com
- username: myaccount@mydomain.local.com
- password: mysecretpassword
- restart: True
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Computer already added to \'{0}\''.format(name)}
current_domain_dic = __salt__['system.get_domain_workgroup']()
if 'Domain' in current_domain_dic:
current_domain = current_domain_dic['Domain']
elif 'Workgroup' in current_domain_dic:
current_domain = 'Workgroup'
else:
current_domain = None
if name.lower() == current_domain.lower():
ret['comment'] = 'Computer already added to \'{0}\''.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Computer will be added to \'{0}\''.format(name)
return ret
result = __salt__['system.join_domain'](domain=name,
username=username,
password=password,
account_ou=account_ou,
account_exists=account_exists,
restart=restart)
if result is not False:
ret['comment'] = 'Computer added to \'{0}\''.format(name)
if restart:
ret['comment'] += '\nSystem will restart'
else:
ret['comment'] += '\nSystem needs to be restarted'
ret['changes'] = {'old': current_domain,
'new': name}
else:
ret['comment'] = 'Computer failed to join \'{0}\''.format(name)
ret['result'] = False
return ret | python | def join_domain(name,
username=None,
password=None,
account_ou=None,
account_exists=False,
restart=False):
'''
Checks if a computer is joined to the Domain. If the computer is not in the
Domain, it will be joined.
Args:
name (str):
The name of the Domain.
username (str):
Username of an account which is authorized to join computers to the
specified domain. Need to be either fully qualified like
user@domain.tld or simply user.
password (str):
Password of the account to add the computer to the Domain.
account_ou (str):
The DN of the OU below which the account for this computer should be
created when joining the domain,
e.g. ou=computers,ou=departm_432,dc=my-company,dc=com.
account_exists (bool):
Needs to be set to ``True`` to allow re-using an existing computer
account.
restart (bool):
Needs to be set to ``True`` to restart the computer after a
successful join.
Example:
.. code-block:: yaml
join_to_domain:
system.join_domain:
- name: mydomain.local.com
- username: myaccount@mydomain.local.com
- password: mysecretpassword
- restart: True
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'Computer already added to \'{0}\''.format(name)}
current_domain_dic = __salt__['system.get_domain_workgroup']()
if 'Domain' in current_domain_dic:
current_domain = current_domain_dic['Domain']
elif 'Workgroup' in current_domain_dic:
current_domain = 'Workgroup'
else:
current_domain = None
if name.lower() == current_domain.lower():
ret['comment'] = 'Computer already added to \'{0}\''.format(name)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Computer will be added to \'{0}\''.format(name)
return ret
result = __salt__['system.join_domain'](domain=name,
username=username,
password=password,
account_ou=account_ou,
account_exists=account_exists,
restart=restart)
if result is not False:
ret['comment'] = 'Computer added to \'{0}\''.format(name)
if restart:
ret['comment'] += '\nSystem will restart'
else:
ret['comment'] += '\nSystem needs to be restarted'
ret['changes'] = {'old': current_domain,
'new': name}
else:
ret['comment'] = 'Computer failed to join \'{0}\''.format(name)
ret['result'] = False
return ret | [
"def",
"join_domain",
"(",
"name",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"account_ou",
"=",
"None",
",",
"account_exists",
"=",
"False",
",",
"restart",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"... | Checks if a computer is joined to the Domain. If the computer is not in the
Domain, it will be joined.
Args:
name (str):
The name of the Domain.
username (str):
Username of an account which is authorized to join computers to the
specified domain. Need to be either fully qualified like
user@domain.tld or simply user.
password (str):
Password of the account to add the computer to the Domain.
account_ou (str):
The DN of the OU below which the account for this computer should be
created when joining the domain,
e.g. ou=computers,ou=departm_432,dc=my-company,dc=com.
account_exists (bool):
Needs to be set to ``True`` to allow re-using an existing computer
account.
restart (bool):
Needs to be set to ``True`` to restart the computer after a
successful join.
Example:
.. code-block:: yaml
join_to_domain:
system.join_domain:
- name: mydomain.local.com
- username: myaccount@mydomain.local.com
- password: mysecretpassword
- restart: True | [
"Checks",
"if",
"a",
"computer",
"is",
"joined",
"to",
"the",
"Domain",
".",
"If",
"the",
"computer",
"is",
"not",
"in",
"the",
"Domain",
"it",
"will",
"be",
"joined",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L228-L315 | train |
saltstack/salt | salt/states/win_system.py | reboot | def reboot(name, message=None, timeout=5, force_close=True, in_seconds=False,
only_on_pending_reboot=True):
'''
Reboot the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a reboot will occur. Whether
this number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool only_on_pending_reboot:
If this is True, the reboot will only occur if the system reports a
pending reboot. If this is False, the reboot will always occur.
The default value is True.
'''
return shutdown(name, message=message, timeout=timeout,
force_close=force_close, reboot=True,
in_seconds=in_seconds,
only_on_pending_reboot=only_on_pending_reboot) | python | def reboot(name, message=None, timeout=5, force_close=True, in_seconds=False,
only_on_pending_reboot=True):
'''
Reboot the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a reboot will occur. Whether
this number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool only_on_pending_reboot:
If this is True, the reboot will only occur if the system reports a
pending reboot. If this is False, the reboot will always occur.
The default value is True.
'''
return shutdown(name, message=message, timeout=timeout,
force_close=force_close, reboot=True,
in_seconds=in_seconds,
only_on_pending_reboot=only_on_pending_reboot) | [
"def",
"reboot",
"(",
"name",
",",
"message",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"force_close",
"=",
"True",
",",
"in_seconds",
"=",
"False",
",",
"only_on_pending_reboot",
"=",
"True",
")",
":",
"return",
"shutdown",
"(",
"name",
",",
"message"... | Reboot the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a reboot will occur. Whether
this number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool only_on_pending_reboot:
If this is True, the reboot will only occur if the system reports a
pending reboot. If this is False, the reboot will always occur.
The default value is True. | [
"Reboot",
"the",
"computer"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L318-L361 | train |
saltstack/salt | salt/states/win_system.py | shutdown | def shutdown(name, message=None, timeout=5, force_close=True, reboot=False,
in_seconds=False, only_on_pending_reboot=False):
'''
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a shutdown will occur. Whether
this number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool reboot:
If this is True, the computer will restart immediately after shutting
down. If False the system flushes all caches to disk and safely powers
down the system.
The default value is False.
:param bool only_on_pending_reboot:
If this is True, the shutdown will only occur if the system reports a
pending reboot. If this is False, the shutdown will always occur.
The default value is False.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if reboot:
action = 'reboot'
else:
action = 'shutdown'
if only_on_pending_reboot and not __salt__['system.get_pending_reboot']():
if __opts__['test']:
ret['comment'] = ('System {0} will be skipped because '
'no reboot is pending').format(action)
else:
ret['comment'] = ('System {0} has been skipped because '
'no reboot was pending').format(action)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Will attempt to schedule a {0}'.format(action)
return ret
ret['result'] = __salt__['system.shutdown'](message=message,
timeout=timeout,
force_close=force_close,
reboot=reboot,
in_seconds=in_seconds,
only_on_pending_reboot=False)
if ret['result']:
ret['changes'] = {'old': 'No reboot or shutdown was scheduled',
'new': 'A {0} has been scheduled'.format(action)}
ret['comment'] = 'Request to {0} was successful'.format(action)
else:
ret['comment'] = 'Request to {0} failed'.format(action)
return ret | python | def shutdown(name, message=None, timeout=5, force_close=True, reboot=False,
in_seconds=False, only_on_pending_reboot=False):
'''
Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a shutdown will occur. Whether
this number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool reboot:
If this is True, the computer will restart immediately after shutting
down. If False the system flushes all caches to disk and safely powers
down the system.
The default value is False.
:param bool only_on_pending_reboot:
If this is True, the shutdown will only occur if the system reports a
pending reboot. If this is False, the shutdown will always occur.
The default value is False.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
if reboot:
action = 'reboot'
else:
action = 'shutdown'
if only_on_pending_reboot and not __salt__['system.get_pending_reboot']():
if __opts__['test']:
ret['comment'] = ('System {0} will be skipped because '
'no reboot is pending').format(action)
else:
ret['comment'] = ('System {0} has been skipped because '
'no reboot was pending').format(action)
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Will attempt to schedule a {0}'.format(action)
return ret
ret['result'] = __salt__['system.shutdown'](message=message,
timeout=timeout,
force_close=force_close,
reboot=reboot,
in_seconds=in_seconds,
only_on_pending_reboot=False)
if ret['result']:
ret['changes'] = {'old': 'No reboot or shutdown was scheduled',
'new': 'A {0} has been scheduled'.format(action)}
ret['comment'] = 'Request to {0} was successful'.format(action)
else:
ret['comment'] = 'Request to {0} failed'.format(action)
return ret | [
"def",
"shutdown",
"(",
"name",
",",
"message",
"=",
"None",
",",
"timeout",
"=",
"5",
",",
"force_close",
"=",
"True",
",",
"reboot",
"=",
"False",
",",
"in_seconds",
"=",
"False",
",",
"only_on_pending_reboot",
"=",
"False",
")",
":",
"ret",
"=",
"{"... | Shutdown the computer
:param str message:
An optional message to display to users. It will also be used as a
comment in the event log entry.
The default value is None.
:param int timeout:
The number of minutes or seconds before a shutdown will occur. Whether
this number represents minutes or seconds depends on the value of
``in_seconds``.
The default value is 5.
:param bool in_seconds:
If this is True, the value of ``timeout`` will be treated as a number
of seconds. If this is False, the value of ``timeout`` will be treated
as a number of minutes.
The default value is False.
:param bool force_close:
If this is True, running applications will be forced to close without
warning. If this is False, running applications will not get the
opportunity to prompt users about unsaved data.
The default value is True.
:param bool reboot:
If this is True, the computer will restart immediately after shutting
down. If False the system flushes all caches to disk and safely powers
down the system.
The default value is False.
:param bool only_on_pending_reboot:
If this is True, the shutdown will only occur if the system reports a
pending reboot. If this is False, the shutdown will always occur.
The default value is False. | [
"Shutdown",
"the",
"computer"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_system.py#L364-L449 | train |
saltstack/salt | salt/states/slack.py | post_message | def post_message(name,
channel,
from_name,
message,
api_key=None,
icon=None):
'''
Send a message to a Slack channel.
.. code-block:: yaml
slack-message:
slack.post_message:
- channel: '#general'
- from_name: SuperAdmin
- message: 'This state was executed successfully.'
- api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15
The following parameters are required:
name
The unique name for this event.
channel
The channel to send the message to. Must be in the format "#channelname" or "@membername".
from_name
The name of that is to be shown in the "from" field.
message
The message that is to be sent to the Slack channel.
The following parameters are optional:
api_key
The api key for Slack to use for authentication,
if not specified in the configuration options of master or minion.
icon
URL to an image to use as the icon for this message
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to Slack: {0}'.format(message)
ret['result'] = None
return ret
if not channel:
ret['comment'] = 'Slack channel is missing: {0}'.format(channel)
return ret
if not from_name:
ret['comment'] = 'Slack from name is missing: {0}'.format(from_name)
return ret
if not message:
ret['comment'] = 'Slack message is missing: {0}'.format(message)
return ret
try:
result = __salt__['slack.post_message'](
channel=channel,
message=message,
from_name=from_name,
api_key=api_key,
icon=icon,
)
except SaltInvocationError as sie:
ret['comment'] = 'Failed to send message ({0}): {1}'.format(sie, name)
else:
if isinstance(result, bool) and result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message ({0}): {1}'.format(result['message'], name)
return ret | python | def post_message(name,
channel,
from_name,
message,
api_key=None,
icon=None):
'''
Send a message to a Slack channel.
.. code-block:: yaml
slack-message:
slack.post_message:
- channel: '#general'
- from_name: SuperAdmin
- message: 'This state was executed successfully.'
- api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15
The following parameters are required:
name
The unique name for this event.
channel
The channel to send the message to. Must be in the format "#channelname" or "@membername".
from_name
The name of that is to be shown in the "from" field.
message
The message that is to be sent to the Slack channel.
The following parameters are optional:
api_key
The api key for Slack to use for authentication,
if not specified in the configuration options of master or minion.
icon
URL to an image to use as the icon for this message
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if __opts__['test']:
ret['comment'] = 'The following message is to be sent to Slack: {0}'.format(message)
ret['result'] = None
return ret
if not channel:
ret['comment'] = 'Slack channel is missing: {0}'.format(channel)
return ret
if not from_name:
ret['comment'] = 'Slack from name is missing: {0}'.format(from_name)
return ret
if not message:
ret['comment'] = 'Slack message is missing: {0}'.format(message)
return ret
try:
result = __salt__['slack.post_message'](
channel=channel,
message=message,
from_name=from_name,
api_key=api_key,
icon=icon,
)
except SaltInvocationError as sie:
ret['comment'] = 'Failed to send message ({0}): {1}'.format(sie, name)
else:
if isinstance(result, bool) and result:
ret['result'] = True
ret['comment'] = 'Sent message: {0}'.format(name)
else:
ret['comment'] = 'Failed to send message ({0}): {1}'.format(result['message'], name)
return ret | [
"def",
"post_message",
"(",
"name",
",",
"channel",
",",
"from_name",
",",
"message",
",",
"api_key",
"=",
"None",
",",
"icon",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"F... | Send a message to a Slack channel.
.. code-block:: yaml
slack-message:
slack.post_message:
- channel: '#general'
- from_name: SuperAdmin
- message: 'This state was executed successfully.'
- api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15
The following parameters are required:
name
The unique name for this event.
channel
The channel to send the message to. Must be in the format "#channelname" or "@membername".
from_name
The name of that is to be shown in the "from" field.
message
The message that is to be sent to the Slack channel.
The following parameters are optional:
api_key
The api key for Slack to use for authentication,
if not specified in the configuration options of master or minion.
icon
URL to an image to use as the icon for this message | [
"Send",
"a",
"message",
"to",
"a",
"Slack",
"channel",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/slack.py#L42-L122 | train |
saltstack/salt | salt/modules/btrfs.py | _parse_btrfs_info | def _parse_btrfs_info(data):
'''
Parse BTRFS device info data.
'''
ret = {}
for line in [line for line in data.split("\n") if line][:-1]:
if line.startswith("Label:"):
line = re.sub(r"Label:\s+", "", line)
label, uuid_ = [tkn.strip() for tkn in line.split("uuid:")]
ret['label'] = label != 'none' and label or None
ret['uuid'] = uuid_
continue
if line.startswith("\tdevid"):
dev_data = re.split(r"\s+", line.strip())
dev_id = dev_data[-1]
ret[dev_id] = {
'device_id': dev_data[1],
'size': dev_data[3],
'used': dev_data[5],
}
return ret | python | def _parse_btrfs_info(data):
'''
Parse BTRFS device info data.
'''
ret = {}
for line in [line for line in data.split("\n") if line][:-1]:
if line.startswith("Label:"):
line = re.sub(r"Label:\s+", "", line)
label, uuid_ = [tkn.strip() for tkn in line.split("uuid:")]
ret['label'] = label != 'none' and label or None
ret['uuid'] = uuid_
continue
if line.startswith("\tdevid"):
dev_data = re.split(r"\s+", line.strip())
dev_id = dev_data[-1]
ret[dev_id] = {
'device_id': dev_data[1],
'size': dev_data[3],
'used': dev_data[5],
}
return ret | [
"def",
"_parse_btrfs_info",
"(",
"data",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"line",
"in",
"[",
"line",
"for",
"line",
"in",
"data",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"line",
"]",
"[",
":",
"-",
"1",
"]",
":",
"if",
"line",
".",
"star... | Parse BTRFS device info data. | [
"Parse",
"BTRFS",
"device",
"info",
"data",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L60-L82 | train |
saltstack/salt | salt/modules/btrfs.py | info | def info(device):
'''
Get BTRFS filesystem information.
CLI Example:
.. code-block:: bash
salt '*' btrfs.info /dev/sda1
'''
out = __salt__['cmd.run_all']("btrfs filesystem show {0}".format(device))
salt.utils.fsutils._verify_run(out)
return _parse_btrfs_info(out['stdout']) | python | def info(device):
'''
Get BTRFS filesystem information.
CLI Example:
.. code-block:: bash
salt '*' btrfs.info /dev/sda1
'''
out = __salt__['cmd.run_all']("btrfs filesystem show {0}".format(device))
salt.utils.fsutils._verify_run(out)
return _parse_btrfs_info(out['stdout']) | [
"def",
"info",
"(",
"device",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"btrfs filesystem show {0}\"",
".",
"format",
"(",
"device",
")",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_verify_run",
"(",
"out",
")",
"return",
... | Get BTRFS filesystem information.
CLI Example:
.. code-block:: bash
salt '*' btrfs.info /dev/sda1 | [
"Get",
"BTRFS",
"filesystem",
"information",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L85-L98 | train |
saltstack/salt | salt/modules/btrfs.py | devices | def devices():
'''
Get known BTRFS formatted devices on the system.
CLI Example:
.. code-block:: bash
salt '*' btrfs.devices
'''
out = __salt__['cmd.run_all']("blkid -o export")
salt.utils.fsutils._verify_run(out)
return salt.utils.fsutils._blkid_output(out['stdout'], fs_type='btrfs') | python | def devices():
'''
Get known BTRFS formatted devices on the system.
CLI Example:
.. code-block:: bash
salt '*' btrfs.devices
'''
out = __salt__['cmd.run_all']("blkid -o export")
salt.utils.fsutils._verify_run(out)
return salt.utils.fsutils._blkid_output(out['stdout'], fs_type='btrfs') | [
"def",
"devices",
"(",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"blkid -o export\"",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_verify_run",
"(",
"out",
")",
"return",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_blkid_o... | Get known BTRFS formatted devices on the system.
CLI Example:
.. code-block:: bash
salt '*' btrfs.devices | [
"Get",
"known",
"BTRFS",
"formatted",
"devices",
"on",
"the",
"system",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L101-L114 | train |
saltstack/salt | salt/modules/btrfs.py | _defragment_mountpoint | def _defragment_mountpoint(mountpoint):
'''
Defragment only one BTRFS mountpoint.
'''
out = __salt__['cmd.run_all']("btrfs filesystem defragment -f {0}".format(mountpoint))
return {
'mount_point': mountpoint,
'passed': not out['stderr'],
'log': out['stderr'] or False,
'range': False,
} | python | def _defragment_mountpoint(mountpoint):
'''
Defragment only one BTRFS mountpoint.
'''
out = __salt__['cmd.run_all']("btrfs filesystem defragment -f {0}".format(mountpoint))
return {
'mount_point': mountpoint,
'passed': not out['stderr'],
'log': out['stderr'] or False,
'range': False,
} | [
"def",
"_defragment_mountpoint",
"(",
"mountpoint",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"btrfs filesystem defragment -f {0}\"",
".",
"format",
"(",
"mountpoint",
")",
")",
"return",
"{",
"'mount_point'",
":",
"mountpoint",
",",
"'pa... | Defragment only one BTRFS mountpoint. | [
"Defragment",
"only",
"one",
"BTRFS",
"mountpoint",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L117-L127 | train |
saltstack/salt | salt/modules/btrfs.py | defragment | def defragment(path):
'''
Defragment mounted BTRFS filesystem.
In order to defragment a filesystem, device should be properly mounted and writable.
If passed a device name, then defragmented whole filesystem, mounted on in.
If passed a moun tpoint of the filesystem, then only this mount point is defragmented.
CLI Example:
.. code-block:: bash
salt '*' btrfs.defragment /dev/sda1
salt '*' btrfs.defragment /path/on/filesystem
'''
is_device = salt.utils.fsutils._is_device(path)
mounts = salt.utils.fsutils._get_mounts("btrfs")
if is_device and not mounts.get(path):
raise CommandExecutionError("Device \"{0}\" is not mounted".format(path))
result = []
if is_device:
for mount_point in mounts[path]:
result.append(_defragment_mountpoint(mount_point['mount_point']))
else:
is_mountpoint = False
for mountpoints in six.itervalues(mounts):
for mpnt in mountpoints:
if path == mpnt['mount_point']:
is_mountpoint = True
break
d_res = _defragment_mountpoint(path)
if not is_mountpoint and not d_res['passed'] and "range ioctl not supported" in d_res['log']:
d_res['log'] = "Range ioctl defragmentation is not supported in this kernel."
if not is_mountpoint:
d_res['mount_point'] = False
d_res['range'] = os.path.exists(path) and path or False
result.append(d_res)
return result | python | def defragment(path):
'''
Defragment mounted BTRFS filesystem.
In order to defragment a filesystem, device should be properly mounted and writable.
If passed a device name, then defragmented whole filesystem, mounted on in.
If passed a moun tpoint of the filesystem, then only this mount point is defragmented.
CLI Example:
.. code-block:: bash
salt '*' btrfs.defragment /dev/sda1
salt '*' btrfs.defragment /path/on/filesystem
'''
is_device = salt.utils.fsutils._is_device(path)
mounts = salt.utils.fsutils._get_mounts("btrfs")
if is_device and not mounts.get(path):
raise CommandExecutionError("Device \"{0}\" is not mounted".format(path))
result = []
if is_device:
for mount_point in mounts[path]:
result.append(_defragment_mountpoint(mount_point['mount_point']))
else:
is_mountpoint = False
for mountpoints in six.itervalues(mounts):
for mpnt in mountpoints:
if path == mpnt['mount_point']:
is_mountpoint = True
break
d_res = _defragment_mountpoint(path)
if not is_mountpoint and not d_res['passed'] and "range ioctl not supported" in d_res['log']:
d_res['log'] = "Range ioctl defragmentation is not supported in this kernel."
if not is_mountpoint:
d_res['mount_point'] = False
d_res['range'] = os.path.exists(path) and path or False
result.append(d_res)
return result | [
"def",
"defragment",
"(",
"path",
")",
":",
"is_device",
"=",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_is_device",
"(",
"path",
")",
"mounts",
"=",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_get_mounts",
"(",
"\"btrfs\"",
")",
"if",
"is_device",
... | Defragment mounted BTRFS filesystem.
In order to defragment a filesystem, device should be properly mounted and writable.
If passed a device name, then defragmented whole filesystem, mounted on in.
If passed a moun tpoint of the filesystem, then only this mount point is defragmented.
CLI Example:
.. code-block:: bash
salt '*' btrfs.defragment /dev/sda1
salt '*' btrfs.defragment /path/on/filesystem | [
"Defragment",
"mounted",
"BTRFS",
"filesystem",
".",
"In",
"order",
"to",
"defragment",
"a",
"filesystem",
"device",
"should",
"be",
"properly",
"mounted",
"and",
"writable",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L130-L171 | train |
saltstack/salt | salt/modules/btrfs.py | features | def features():
'''
List currently available BTRFS features.
CLI Example:
.. code-block:: bash
salt '*' btrfs.mkfs_features
'''
out = __salt__['cmd.run_all']("mkfs.btrfs -O list-all")
salt.utils.fsutils._verify_run(out)
ret = {}
for line in [re.sub(r"\s+", " ", line) for line in out['stderr'].split("\n") if " - " in line]:
option, description = line.split(" - ", 1)
ret[option] = description
return ret | python | def features():
'''
List currently available BTRFS features.
CLI Example:
.. code-block:: bash
salt '*' btrfs.mkfs_features
'''
out = __salt__['cmd.run_all']("mkfs.btrfs -O list-all")
salt.utils.fsutils._verify_run(out)
ret = {}
for line in [re.sub(r"\s+", " ", line) for line in out['stderr'].split("\n") if " - " in line]:
option, description = line.split(" - ", 1)
ret[option] = description
return ret | [
"def",
"features",
"(",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"mkfs.btrfs -O list-all\"",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_verify_run",
"(",
"out",
")",
"ret",
"=",
"{",
"}",
"for",
"line",
"in",
"[",
"re"... | List currently available BTRFS features.
CLI Example:
.. code-block:: bash
salt '*' btrfs.mkfs_features | [
"List",
"currently",
"available",
"BTRFS",
"features",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L174-L192 | train |
saltstack/salt | salt/modules/btrfs.py | _usage_overall | def _usage_overall(raw):
'''
Parse usage/overall.
'''
data = {}
for line in raw.split("\n")[1:]:
keyset = [item.strip() for item in re.sub(r"\s+", " ", line).split(":", 1) if item.strip()]
if len(keyset) == 2:
key = re.sub(r"[()]", "", keyset[0]).replace(" ", "_").lower()
if key in ['free_estimated', 'global_reserve']: # An extra field
subk = keyset[1].split("(")
data[key] = subk[0].strip()
subk = subk[1].replace(")", "").split(": ")
data["{0}_{1}".format(key, subk[0])] = subk[1]
else:
data[key] = keyset[1]
return data | python | def _usage_overall(raw):
'''
Parse usage/overall.
'''
data = {}
for line in raw.split("\n")[1:]:
keyset = [item.strip() for item in re.sub(r"\s+", " ", line).split(":", 1) if item.strip()]
if len(keyset) == 2:
key = re.sub(r"[()]", "", keyset[0]).replace(" ", "_").lower()
if key in ['free_estimated', 'global_reserve']: # An extra field
subk = keyset[1].split("(")
data[key] = subk[0].strip()
subk = subk[1].replace(")", "").split(": ")
data["{0}_{1}".format(key, subk[0])] = subk[1]
else:
data[key] = keyset[1]
return data | [
"def",
"_usage_overall",
"(",
"raw",
")",
":",
"data",
"=",
"{",
"}",
"for",
"line",
"in",
"raw",
".",
"split",
"(",
"\"\\n\"",
")",
"[",
"1",
":",
"]",
":",
"keyset",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"re",
".",
... | Parse usage/overall. | [
"Parse",
"usage",
"/",
"overall",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L195-L212 | train |
saltstack/salt | salt/modules/btrfs.py | _usage_specific | def _usage_specific(raw):
'''
Parse usage/specific.
'''
get_key = lambda val: dict([tuple(val.split(":")), ])
raw = raw.split("\n")
section, size, used = raw[0].split(" ")
section = section.replace(",", "_").replace(":", "").lower()
data = {}
data[section] = {}
for val in [size, used]:
data[section].update(get_key(val.replace(",", "")))
for devices in raw[1:]:
data[section].update(get_key(re.sub(r"\s+", ":", devices.strip())))
return data | python | def _usage_specific(raw):
'''
Parse usage/specific.
'''
get_key = lambda val: dict([tuple(val.split(":")), ])
raw = raw.split("\n")
section, size, used = raw[0].split(" ")
section = section.replace(",", "_").replace(":", "").lower()
data = {}
data[section] = {}
for val in [size, used]:
data[section].update(get_key(val.replace(",", "")))
for devices in raw[1:]:
data[section].update(get_key(re.sub(r"\s+", ":", devices.strip())))
return data | [
"def",
"_usage_specific",
"(",
"raw",
")",
":",
"get_key",
"=",
"lambda",
"val",
":",
"dict",
"(",
"[",
"tuple",
"(",
"val",
".",
"split",
"(",
"\":\"",
")",
")",
",",
"]",
")",
"raw",
"=",
"raw",
".",
"split",
"(",
"\"\\n\"",
")",
"section",
","... | Parse usage/specific. | [
"Parse",
"usage",
"/",
"specific",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L215-L233 | train |
saltstack/salt | salt/modules/btrfs.py | _usage_unallocated | def _usage_unallocated(raw):
'''
Parse usage/unallocated.
'''
ret = {}
for line in raw.split("\n")[1:]:
keyset = re.sub(r"\s+", " ", line.strip()).split(" ")
if len(keyset) == 2:
ret[keyset[0]] = keyset[1]
return ret | python | def _usage_unallocated(raw):
'''
Parse usage/unallocated.
'''
ret = {}
for line in raw.split("\n")[1:]:
keyset = re.sub(r"\s+", " ", line.strip()).split(" ")
if len(keyset) == 2:
ret[keyset[0]] = keyset[1]
return ret | [
"def",
"_usage_unallocated",
"(",
"raw",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"line",
"in",
"raw",
".",
"split",
"(",
"\"\\n\"",
")",
"[",
"1",
":",
"]",
":",
"keyset",
"=",
"re",
".",
"sub",
"(",
"r\"\\s+\"",
",",
"\" \"",
",",
"line",
".",
... | Parse usage/unallocated. | [
"Parse",
"usage",
"/",
"unallocated",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L236-L246 | train |
saltstack/salt | salt/modules/btrfs.py | usage | def usage(path):
'''
Show in which disk the chunks are allocated.
CLI Example:
.. code-block:: bash
salt '*' btrfs.usage /your/mountpoint
'''
out = __salt__['cmd.run_all']("btrfs filesystem usage {0}".format(path))
salt.utils.fsutils._verify_run(out)
ret = {}
for section in out['stdout'].split("\n\n"):
if section.startswith("Overall:\n"):
ret['overall'] = _usage_overall(section)
elif section.startswith("Unallocated:\n"):
ret['unallocated'] = _usage_unallocated(section)
else:
ret.update(_usage_specific(section))
return ret | python | def usage(path):
'''
Show in which disk the chunks are allocated.
CLI Example:
.. code-block:: bash
salt '*' btrfs.usage /your/mountpoint
'''
out = __salt__['cmd.run_all']("btrfs filesystem usage {0}".format(path))
salt.utils.fsutils._verify_run(out)
ret = {}
for section in out['stdout'].split("\n\n"):
if section.startswith("Overall:\n"):
ret['overall'] = _usage_overall(section)
elif section.startswith("Unallocated:\n"):
ret['unallocated'] = _usage_unallocated(section)
else:
ret.update(_usage_specific(section))
return ret | [
"def",
"usage",
"(",
"path",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"btrfs filesystem usage {0}\"",
".",
"format",
"(",
"path",
")",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_verify_run",
"(",
"out",
")",
"ret",
"=",
... | Show in which disk the chunks are allocated.
CLI Example:
.. code-block:: bash
salt '*' btrfs.usage /your/mountpoint | [
"Show",
"in",
"which",
"disk",
"the",
"chunks",
"are",
"allocated",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L249-L271 | train |
saltstack/salt | salt/modules/btrfs.py | mkfs | def mkfs(*devices, **kwargs):
'''
Create a file system on the specified device. By default wipes out with force.
General options:
* **allocsize**: Specify the BTRFS offset from the start of the device.
* **bytecount**: Specify the size of the resultant filesystem.
* **nodesize**: Node size.
* **leafsize**: Specify the nodesize, the tree block size in which btrfs stores data.
* **noforce**: Prevent force overwrite when an existing filesystem is detected on the device.
* **sectorsize**: Specify the sectorsize, the minimum data block allocation unit.
* **nodiscard**: Do not perform whole device TRIM operation by default.
* **uuid**: Pass UUID or pass True to generate one.
Options:
* **dto**: (raid0|raid1|raid5|raid6|raid10|single|dup)
Specify how the data must be spanned across the devices specified.
* **mto**: (raid0|raid1|raid5|raid6|raid10|single|dup)
Specify how metadata must be spanned across the devices specified.
* **fts**: Features (call ``salt <host> btrfs.features`` for full list of available features)
See the ``mkfs.btrfs(8)`` manpage for a more complete description of corresponding options description.
CLI Example:
.. code-block:: bash
salt '*' btrfs.mkfs /dev/sda1
salt '*' btrfs.mkfs /dev/sda1 noforce=True
'''
if not devices:
raise CommandExecutionError("No devices specified")
mounts = salt.utils.fsutils._get_mounts("btrfs")
for device in devices:
if mounts.get(device):
raise CommandExecutionError("Device \"{0}\" should not be mounted".format(device))
cmd = ["mkfs.btrfs"]
dto = kwargs.get("dto")
mto = kwargs.get("mto")
if len(devices) == 1:
if dto:
cmd.append("-d single")
if mto:
cmd.append("-m single")
else:
if dto:
cmd.append("-d {0}".format(dto))
if mto:
cmd.append("-m {0}".format(mto))
for key, option in [("-l", "leafsize"), ("-L", "label"), ("-O", "fts"),
("-A", "allocsize"), ("-b", "bytecount"), ("-n", "nodesize"),
("-s", "sectorsize")]:
if option == 'label' and option in kwargs:
kwargs['label'] = "'{0}'".format(kwargs["label"])
if kwargs.get(option):
cmd.append("{0} {1}".format(key, kwargs.get(option)))
if kwargs.get("uuid"):
cmd.append("-U {0}".format(kwargs.get("uuid") is True and uuid.uuid1() or kwargs.get("uuid")))
if kwargs.get("nodiscard"):
cmd.append("-K")
if not kwargs.get("noforce"):
cmd.append("-f")
cmd.extend(devices)
out = __salt__['cmd.run_all'](' '.join(cmd))
salt.utils.fsutils._verify_run(out)
ret = {'log': out['stdout']}
ret.update(__salt__['btrfs.info'](devices[0]))
return ret | python | def mkfs(*devices, **kwargs):
'''
Create a file system on the specified device. By default wipes out with force.
General options:
* **allocsize**: Specify the BTRFS offset from the start of the device.
* **bytecount**: Specify the size of the resultant filesystem.
* **nodesize**: Node size.
* **leafsize**: Specify the nodesize, the tree block size in which btrfs stores data.
* **noforce**: Prevent force overwrite when an existing filesystem is detected on the device.
* **sectorsize**: Specify the sectorsize, the minimum data block allocation unit.
* **nodiscard**: Do not perform whole device TRIM operation by default.
* **uuid**: Pass UUID or pass True to generate one.
Options:
* **dto**: (raid0|raid1|raid5|raid6|raid10|single|dup)
Specify how the data must be spanned across the devices specified.
* **mto**: (raid0|raid1|raid5|raid6|raid10|single|dup)
Specify how metadata must be spanned across the devices specified.
* **fts**: Features (call ``salt <host> btrfs.features`` for full list of available features)
See the ``mkfs.btrfs(8)`` manpage for a more complete description of corresponding options description.
CLI Example:
.. code-block:: bash
salt '*' btrfs.mkfs /dev/sda1
salt '*' btrfs.mkfs /dev/sda1 noforce=True
'''
if not devices:
raise CommandExecutionError("No devices specified")
mounts = salt.utils.fsutils._get_mounts("btrfs")
for device in devices:
if mounts.get(device):
raise CommandExecutionError("Device \"{0}\" should not be mounted".format(device))
cmd = ["mkfs.btrfs"]
dto = kwargs.get("dto")
mto = kwargs.get("mto")
if len(devices) == 1:
if dto:
cmd.append("-d single")
if mto:
cmd.append("-m single")
else:
if dto:
cmd.append("-d {0}".format(dto))
if mto:
cmd.append("-m {0}".format(mto))
for key, option in [("-l", "leafsize"), ("-L", "label"), ("-O", "fts"),
("-A", "allocsize"), ("-b", "bytecount"), ("-n", "nodesize"),
("-s", "sectorsize")]:
if option == 'label' and option in kwargs:
kwargs['label'] = "'{0}'".format(kwargs["label"])
if kwargs.get(option):
cmd.append("{0} {1}".format(key, kwargs.get(option)))
if kwargs.get("uuid"):
cmd.append("-U {0}".format(kwargs.get("uuid") is True and uuid.uuid1() or kwargs.get("uuid")))
if kwargs.get("nodiscard"):
cmd.append("-K")
if not kwargs.get("noforce"):
cmd.append("-f")
cmd.extend(devices)
out = __salt__['cmd.run_all'](' '.join(cmd))
salt.utils.fsutils._verify_run(out)
ret = {'log': out['stdout']}
ret.update(__salt__['btrfs.info'](devices[0]))
return ret | [
"def",
"mkfs",
"(",
"*",
"devices",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"devices",
":",
"raise",
"CommandExecutionError",
"(",
"\"No devices specified\"",
")",
"mounts",
"=",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_get_mounts",
"(",
"\"btr... | Create a file system on the specified device. By default wipes out with force.
General options:
* **allocsize**: Specify the BTRFS offset from the start of the device.
* **bytecount**: Specify the size of the resultant filesystem.
* **nodesize**: Node size.
* **leafsize**: Specify the nodesize, the tree block size in which btrfs stores data.
* **noforce**: Prevent force overwrite when an existing filesystem is detected on the device.
* **sectorsize**: Specify the sectorsize, the minimum data block allocation unit.
* **nodiscard**: Do not perform whole device TRIM operation by default.
* **uuid**: Pass UUID or pass True to generate one.
Options:
* **dto**: (raid0|raid1|raid5|raid6|raid10|single|dup)
Specify how the data must be spanned across the devices specified.
* **mto**: (raid0|raid1|raid5|raid6|raid10|single|dup)
Specify how metadata must be spanned across the devices specified.
* **fts**: Features (call ``salt <host> btrfs.features`` for full list of available features)
See the ``mkfs.btrfs(8)`` manpage for a more complete description of corresponding options description.
CLI Example:
.. code-block:: bash
salt '*' btrfs.mkfs /dev/sda1
salt '*' btrfs.mkfs /dev/sda1 noforce=True | [
"Create",
"a",
"file",
"system",
"on",
"the",
"specified",
"device",
".",
"By",
"default",
"wipes",
"out",
"with",
"force",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L274-L354 | train |
saltstack/salt | salt/modules/btrfs.py | resize | def resize(mountpoint, size):
'''
Resize filesystem.
General options:
* **mountpoint**: Specify the BTRFS mountpoint to resize.
* **size**: ([+/-]<newsize>[kKmMgGtTpPeE]|max) Specify the new size of the target.
CLI Example:
.. code-block:: bash
salt '*' btrfs.resize /mountpoint size=+1g
salt '*' btrfs.resize /dev/sda1 size=max
'''
if size == 'max':
if not salt.utils.fsutils._is_device(mountpoint):
raise CommandExecutionError("Mountpoint \"{0}\" should be a valid device".format(mountpoint))
if not salt.utils.fsutils._get_mounts("btrfs").get(mountpoint):
raise CommandExecutionError("Device \"{0}\" should be mounted".format(mountpoint))
elif len(size) < 3 or size[0] not in '-+' \
or size[-1] not in 'kKmMgGtTpPeE' or re.sub(r"\d", "", size[1:][:-1]):
raise CommandExecutionError("Unknown size: \"{0}\". Expected: [+/-]<newsize>[kKmMgGtTpPeE]|max".format(size))
out = __salt__['cmd.run_all']('btrfs filesystem resize {0} {1}'.format(size, mountpoint))
salt.utils.fsutils._verify_run(out)
ret = {'log': out['stdout']}
ret.update(__salt__['btrfs.info'](mountpoint))
return ret | python | def resize(mountpoint, size):
'''
Resize filesystem.
General options:
* **mountpoint**: Specify the BTRFS mountpoint to resize.
* **size**: ([+/-]<newsize>[kKmMgGtTpPeE]|max) Specify the new size of the target.
CLI Example:
.. code-block:: bash
salt '*' btrfs.resize /mountpoint size=+1g
salt '*' btrfs.resize /dev/sda1 size=max
'''
if size == 'max':
if not salt.utils.fsutils._is_device(mountpoint):
raise CommandExecutionError("Mountpoint \"{0}\" should be a valid device".format(mountpoint))
if not salt.utils.fsutils._get_mounts("btrfs").get(mountpoint):
raise CommandExecutionError("Device \"{0}\" should be mounted".format(mountpoint))
elif len(size) < 3 or size[0] not in '-+' \
or size[-1] not in 'kKmMgGtTpPeE' or re.sub(r"\d", "", size[1:][:-1]):
raise CommandExecutionError("Unknown size: \"{0}\". Expected: [+/-]<newsize>[kKmMgGtTpPeE]|max".format(size))
out = __salt__['cmd.run_all']('btrfs filesystem resize {0} {1}'.format(size, mountpoint))
salt.utils.fsutils._verify_run(out)
ret = {'log': out['stdout']}
ret.update(__salt__['btrfs.info'](mountpoint))
return ret | [
"def",
"resize",
"(",
"mountpoint",
",",
"size",
")",
":",
"if",
"size",
"==",
"'max'",
":",
"if",
"not",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_is_device",
"(",
"mountpoint",
")",
":",
"raise",
"CommandExecutionError",
"(",
"\"Mountpoint \\\"{0}\\\" s... | Resize filesystem.
General options:
* **mountpoint**: Specify the BTRFS mountpoint to resize.
* **size**: ([+/-]<newsize>[kKmMgGtTpPeE]|max) Specify the new size of the target.
CLI Example:
.. code-block:: bash
salt '*' btrfs.resize /mountpoint size=+1g
salt '*' btrfs.resize /dev/sda1 size=max | [
"Resize",
"filesystem",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L357-L389 | train |
saltstack/salt | salt/modules/btrfs.py | convert | def convert(device, permanent=False, keeplf=False):
'''
Convert ext2/3/4 to BTRFS. Device should be mounted.
Filesystem can be converted temporarily so the further processing and rollback is possible,
or permanently, where previous extended filesystem image gets deleted. Please note, permanent
conversion takes a while as BTRFS filesystem needs to be properly rebalanced afterwards.
General options:
* **permanent**: Specify if the migration should be permanent (false by default)
* **keeplf**: Keep ``lost+found`` of the partition (removed by default,
but still in the image, if not permanent migration)
CLI Example:
.. code-block:: bash
salt '*' btrfs.convert /dev/sda1
salt '*' btrfs.convert /dev/sda1 permanent=True
'''
out = __salt__['cmd.run_all']("blkid -o export")
salt.utils.fsutils._verify_run(out)
devices = salt.utils.fsutils._blkid_output(out['stdout'])
if not devices.get(device):
raise CommandExecutionError("The device \"{0}\" was is not found.".format(device))
if not devices[device]["type"] in ['ext2', 'ext3', 'ext4']:
raise CommandExecutionError("The device \"{0}\" is a \"{1}\" file system.".format(
device, devices[device]["type"]))
mountpoint = salt.utils.fsutils._get_mounts(devices[device]["type"]).get(
device, [{'mount_point': None}])[0].get('mount_point')
if mountpoint == '/':
raise CommandExecutionError("""One does not simply converts a root filesystem!
Converting an extended root filesystem to BTRFS is a careful
and lengthy process, among other steps including the following
requirements:
1. Proper verified backup.
2. System outage.
3. Offline system access.
For further details, please refer to your OS vendor
documentation regarding this topic.
""")
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("umount {0}".format(device)))
ret = {
'before': {
'fsck_status': _fsck_ext(device),
'mount_point': mountpoint,
'type': devices[device]["type"],
}
}
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("btrfs-convert {0}".format(device)))
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("mount {0} {1}".format(device, mountpoint)))
# Refresh devices
out = __salt__['cmd.run_all']("blkid -o export")
salt.utils.fsutils._verify_run(out)
devices = salt.utils.fsutils._blkid_output(out['stdout'])
ret['after'] = {
'fsck_status': "N/A", # ToDO
'mount_point': mountpoint,
'type': devices[device]["type"],
}
# Post-migration procedures
image_path = "{0}/ext2_saved".format(mountpoint)
orig_fstype = ret['before']['type']
if not os.path.exists(image_path):
raise CommandExecutionError(
"BTRFS migration went wrong: the image \"{0}\" not found!".format(image_path))
if not permanent:
ret['after']['{0}_image'.format(orig_fstype)] = image_path
ret['after']['{0}_image_info'.format(orig_fstype)] = os.popen(
"file {0}/image".format(image_path)).read().strip()
else:
ret['after']['{0}_image'.format(orig_fstype)] = 'removed'
ret['after']['{0}_image_info'.format(orig_fstype)] = 'N/A'
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("btrfs subvolume delete {0}".format(image_path)))
out = __salt__['cmd.run_all']("btrfs filesystem balance {0}".format(mountpoint))
salt.utils.fsutils._verify_run(out)
ret['after']['balance_log'] = out['stdout']
lost_found = "{0}/lost+found".format(mountpoint)
if os.path.exists(lost_found) and not keeplf:
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("rm -rf {0}".format(lost_found)))
return ret | python | def convert(device, permanent=False, keeplf=False):
'''
Convert ext2/3/4 to BTRFS. Device should be mounted.
Filesystem can be converted temporarily so the further processing and rollback is possible,
or permanently, where previous extended filesystem image gets deleted. Please note, permanent
conversion takes a while as BTRFS filesystem needs to be properly rebalanced afterwards.
General options:
* **permanent**: Specify if the migration should be permanent (false by default)
* **keeplf**: Keep ``lost+found`` of the partition (removed by default,
but still in the image, if not permanent migration)
CLI Example:
.. code-block:: bash
salt '*' btrfs.convert /dev/sda1
salt '*' btrfs.convert /dev/sda1 permanent=True
'''
out = __salt__['cmd.run_all']("blkid -o export")
salt.utils.fsutils._verify_run(out)
devices = salt.utils.fsutils._blkid_output(out['stdout'])
if not devices.get(device):
raise CommandExecutionError("The device \"{0}\" was is not found.".format(device))
if not devices[device]["type"] in ['ext2', 'ext3', 'ext4']:
raise CommandExecutionError("The device \"{0}\" is a \"{1}\" file system.".format(
device, devices[device]["type"]))
mountpoint = salt.utils.fsutils._get_mounts(devices[device]["type"]).get(
device, [{'mount_point': None}])[0].get('mount_point')
if mountpoint == '/':
raise CommandExecutionError("""One does not simply converts a root filesystem!
Converting an extended root filesystem to BTRFS is a careful
and lengthy process, among other steps including the following
requirements:
1. Proper verified backup.
2. System outage.
3. Offline system access.
For further details, please refer to your OS vendor
documentation regarding this topic.
""")
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("umount {0}".format(device)))
ret = {
'before': {
'fsck_status': _fsck_ext(device),
'mount_point': mountpoint,
'type': devices[device]["type"],
}
}
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("btrfs-convert {0}".format(device)))
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("mount {0} {1}".format(device, mountpoint)))
# Refresh devices
out = __salt__['cmd.run_all']("blkid -o export")
salt.utils.fsutils._verify_run(out)
devices = salt.utils.fsutils._blkid_output(out['stdout'])
ret['after'] = {
'fsck_status': "N/A", # ToDO
'mount_point': mountpoint,
'type': devices[device]["type"],
}
# Post-migration procedures
image_path = "{0}/ext2_saved".format(mountpoint)
orig_fstype = ret['before']['type']
if not os.path.exists(image_path):
raise CommandExecutionError(
"BTRFS migration went wrong: the image \"{0}\" not found!".format(image_path))
if not permanent:
ret['after']['{0}_image'.format(orig_fstype)] = image_path
ret['after']['{0}_image_info'.format(orig_fstype)] = os.popen(
"file {0}/image".format(image_path)).read().strip()
else:
ret['after']['{0}_image'.format(orig_fstype)] = 'removed'
ret['after']['{0}_image_info'.format(orig_fstype)] = 'N/A'
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("btrfs subvolume delete {0}".format(image_path)))
out = __salt__['cmd.run_all']("btrfs filesystem balance {0}".format(mountpoint))
salt.utils.fsutils._verify_run(out)
ret['after']['balance_log'] = out['stdout']
lost_found = "{0}/lost+found".format(mountpoint)
if os.path.exists(lost_found) and not keeplf:
salt.utils.fsutils._verify_run(__salt__['cmd.run_all']("rm -rf {0}".format(lost_found)))
return ret | [
"def",
"convert",
"(",
"device",
",",
"permanent",
"=",
"False",
",",
"keeplf",
"=",
"False",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"blkid -o export\"",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_verify_run",
"(",
"ou... | Convert ext2/3/4 to BTRFS. Device should be mounted.
Filesystem can be converted temporarily so the further processing and rollback is possible,
or permanently, where previous extended filesystem image gets deleted. Please note, permanent
conversion takes a while as BTRFS filesystem needs to be properly rebalanced afterwards.
General options:
* **permanent**: Specify if the migration should be permanent (false by default)
* **keeplf**: Keep ``lost+found`` of the partition (removed by default,
but still in the image, if not permanent migration)
CLI Example:
.. code-block:: bash
salt '*' btrfs.convert /dev/sda1
salt '*' btrfs.convert /dev/sda1 permanent=True | [
"Convert",
"ext2",
"/",
"3",
"/",
"4",
"to",
"BTRFS",
".",
"Device",
"should",
"be",
"mounted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L413-L511 | train |
saltstack/salt | salt/modules/btrfs.py | _restripe | def _restripe(mountpoint, direction, *devices, **kwargs):
'''
Restripe BTRFS: add or remove devices from the particular mounted filesystem.
'''
fs_log = []
if salt.utils.fsutils._is_device(mountpoint):
raise CommandExecutionError(
"Mountpount expected, while device \"{0}\" specified".format(mountpoint))
mounted = False
for device, mntpoints in six.iteritems(salt.utils.fsutils._get_mounts("btrfs")):
for mntdata in mntpoints:
if mntdata['mount_point'] == mountpoint:
mounted = True
break
if not mounted:
raise CommandExecutionError(
"No BTRFS device mounted on \"{0}\" mountpoint".format(mountpoint))
if not devices:
raise CommandExecutionError("No devices specified.")
available_devices = __salt__['btrfs.devices']()
for device in devices:
if device not in six.iterkeys(available_devices):
raise CommandExecutionError("Device \"{0}\" is not recognized".format(device))
cmd = ['btrfs device {0}'.format(direction)]
for device in devices:
cmd.append(device)
if direction == 'add':
if kwargs.get("nodiscard"):
cmd.append("-K")
if kwargs.get("force"):
cmd.append("-f")
cmd.append(mountpoint)
out = __salt__['cmd.run_all'](' '.join(cmd))
salt.utils.fsutils._verify_run(out)
if out['stdout']:
fs_log.append(out['stdout'])
if direction == 'add':
out = None
data_conversion = kwargs.get("dc")
meta_conversion = kwargs.get("mc")
if data_conversion and meta_conversion:
out = __salt__['cmd.run_all'](
"btrfs balance start -dconvert={0} -mconvert={1} {2}".format(
data_conversion, meta_conversion, mountpoint))
else:
out = __salt__['cmd.run_all']("btrfs filesystem balance {0}".format(mountpoint))
salt.utils.fsutils._verify_run(out)
if out['stdout']:
fs_log.append(out['stdout'])
# Summarize the result
ret = {}
if fs_log:
ret.update({'log': '\n'.join(fs_log)})
ret.update(__salt__['btrfs.info'](mountpoint))
return ret | python | def _restripe(mountpoint, direction, *devices, **kwargs):
'''
Restripe BTRFS: add or remove devices from the particular mounted filesystem.
'''
fs_log = []
if salt.utils.fsutils._is_device(mountpoint):
raise CommandExecutionError(
"Mountpount expected, while device \"{0}\" specified".format(mountpoint))
mounted = False
for device, mntpoints in six.iteritems(salt.utils.fsutils._get_mounts("btrfs")):
for mntdata in mntpoints:
if mntdata['mount_point'] == mountpoint:
mounted = True
break
if not mounted:
raise CommandExecutionError(
"No BTRFS device mounted on \"{0}\" mountpoint".format(mountpoint))
if not devices:
raise CommandExecutionError("No devices specified.")
available_devices = __salt__['btrfs.devices']()
for device in devices:
if device not in six.iterkeys(available_devices):
raise CommandExecutionError("Device \"{0}\" is not recognized".format(device))
cmd = ['btrfs device {0}'.format(direction)]
for device in devices:
cmd.append(device)
if direction == 'add':
if kwargs.get("nodiscard"):
cmd.append("-K")
if kwargs.get("force"):
cmd.append("-f")
cmd.append(mountpoint)
out = __salt__['cmd.run_all'](' '.join(cmd))
salt.utils.fsutils._verify_run(out)
if out['stdout']:
fs_log.append(out['stdout'])
if direction == 'add':
out = None
data_conversion = kwargs.get("dc")
meta_conversion = kwargs.get("mc")
if data_conversion and meta_conversion:
out = __salt__['cmd.run_all'](
"btrfs balance start -dconvert={0} -mconvert={1} {2}".format(
data_conversion, meta_conversion, mountpoint))
else:
out = __salt__['cmd.run_all']("btrfs filesystem balance {0}".format(mountpoint))
salt.utils.fsutils._verify_run(out)
if out['stdout']:
fs_log.append(out['stdout'])
# Summarize the result
ret = {}
if fs_log:
ret.update({'log': '\n'.join(fs_log)})
ret.update(__salt__['btrfs.info'](mountpoint))
return ret | [
"def",
"_restripe",
"(",
"mountpoint",
",",
"direction",
",",
"*",
"devices",
",",
"*",
"*",
"kwargs",
")",
":",
"fs_log",
"=",
"[",
"]",
"if",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_is_device",
"(",
"mountpoint",
")",
":",
"raise",
"CommandExecu... | Restripe BTRFS: add or remove devices from the particular mounted filesystem. | [
"Restripe",
"BTRFS",
":",
"add",
"or",
"remove",
"devices",
"from",
"the",
"particular",
"mounted",
"filesystem",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L514-L580 | train |
saltstack/salt | salt/modules/btrfs.py | _parse_proplist | def _parse_proplist(data):
'''
Parse properties list.
'''
out = {}
for line in data.split("\n"):
line = re.split(r"\s+", line, 1)
if len(line) == 2:
out[line[0]] = line[1]
return out | python | def _parse_proplist(data):
'''
Parse properties list.
'''
out = {}
for line in data.split("\n"):
line = re.split(r"\s+", line, 1)
if len(line) == 2:
out[line[0]] = line[1]
return out | [
"def",
"_parse_proplist",
"(",
"data",
")",
":",
"out",
"=",
"{",
"}",
"for",
"line",
"in",
"data",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"line",
"=",
"re",
".",
"split",
"(",
"r\"\\s+\"",
",",
"line",
",",
"1",
")",
"if",
"len",
"(",
"line",
... | Parse properties list. | [
"Parse",
"properties",
"list",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L614-L624 | train |
saltstack/salt | salt/modules/btrfs.py | properties | def properties(obj, type=None, set=None):
'''
List properties for given btrfs object. The object can be path of BTRFS device,
mount point, or any directories/files inside the BTRFS filesystem.
General options:
* **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice].
* **force**: Force overwrite existing filesystem on the disk
* **set**: <key=value,key1=value1...> Options for a filesystem properties.
CLI Example:
.. code-block:: bash
salt '*' btrfs.properties /mountpoint
salt '*' btrfs.properties /dev/sda1 type=subvol set='ro=false,label="My Storage"'
'''
if type and type not in ['s', 'subvol', 'f', 'filesystem', 'i', 'inode', 'd', 'device']:
raise CommandExecutionError("Unknown property type: \"{0}\" specified".format(type))
cmd = ['btrfs']
cmd.append('property')
cmd.append(set and 'set' or 'list')
if type:
cmd.append('-t{0}'.format(type))
cmd.append(obj)
if set:
try:
for key, value in [[item.strip() for item in keyset.split("=")]
for keyset in set.split(",")]:
cmd.append(key)
cmd.append(value)
except Exception as ex:
raise CommandExecutionError(ex)
out = __salt__['cmd.run_all'](' '.join(cmd))
salt.utils.fsutils._verify_run(out)
if not set:
ret = {}
for prop, descr in six.iteritems(_parse_proplist(out['stdout'])):
ret[prop] = {'description': descr}
value = __salt__['cmd.run_all'](
"btrfs property get {0} {1}".format(obj, prop))['stdout']
ret[prop]['value'] = value and value.split("=")[-1] or "N/A"
return ret | python | def properties(obj, type=None, set=None):
'''
List properties for given btrfs object. The object can be path of BTRFS device,
mount point, or any directories/files inside the BTRFS filesystem.
General options:
* **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice].
* **force**: Force overwrite existing filesystem on the disk
* **set**: <key=value,key1=value1...> Options for a filesystem properties.
CLI Example:
.. code-block:: bash
salt '*' btrfs.properties /mountpoint
salt '*' btrfs.properties /dev/sda1 type=subvol set='ro=false,label="My Storage"'
'''
if type and type not in ['s', 'subvol', 'f', 'filesystem', 'i', 'inode', 'd', 'device']:
raise CommandExecutionError("Unknown property type: \"{0}\" specified".format(type))
cmd = ['btrfs']
cmd.append('property')
cmd.append(set and 'set' or 'list')
if type:
cmd.append('-t{0}'.format(type))
cmd.append(obj)
if set:
try:
for key, value in [[item.strip() for item in keyset.split("=")]
for keyset in set.split(",")]:
cmd.append(key)
cmd.append(value)
except Exception as ex:
raise CommandExecutionError(ex)
out = __salt__['cmd.run_all'](' '.join(cmd))
salt.utils.fsutils._verify_run(out)
if not set:
ret = {}
for prop, descr in six.iteritems(_parse_proplist(out['stdout'])):
ret[prop] = {'description': descr}
value = __salt__['cmd.run_all'](
"btrfs property get {0} {1}".format(obj, prop))['stdout']
ret[prop]['value'] = value and value.split("=")[-1] or "N/A"
return ret | [
"def",
"properties",
"(",
"obj",
",",
"type",
"=",
"None",
",",
"set",
"=",
"None",
")",
":",
"if",
"type",
"and",
"type",
"not",
"in",
"[",
"'s'",
",",
"'subvol'",
",",
"'f'",
",",
"'filesystem'",
",",
"'i'",
",",
"'inode'",
",",
"'d'",
",",
"'d... | List properties for given btrfs object. The object can be path of BTRFS device,
mount point, or any directories/files inside the BTRFS filesystem.
General options:
* **type**: Possible types are s[ubvol], f[ilesystem], i[node] and d[evice].
* **force**: Force overwrite existing filesystem on the disk
* **set**: <key=value,key1=value1...> Options for a filesystem properties.
CLI Example:
.. code-block:: bash
salt '*' btrfs.properties /mountpoint
salt '*' btrfs.properties /dev/sda1 type=subvol set='ro=false,label="My Storage"' | [
"List",
"properties",
"for",
"given",
"btrfs",
"object",
".",
"The",
"object",
"can",
"be",
"path",
"of",
"BTRFS",
"device",
"mount",
"point",
"or",
"any",
"directories",
"/",
"files",
"inside",
"the",
"BTRFS",
"filesystem",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L627-L675 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_create | def subvolume_create(name, dest=None, qgroupids=None):
'''
Create subvolume `name` in `dest`.
Return True if the subvolume is created, False is the subvolume is
already there.
name
Name of the new subvolume
dest
If not given, the subvolume will be created in the current
directory, if given will be in /dest/name
qgroupids
Add the newly created subcolume to a qgroup. This parameter
is a list
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_create var
salt '*' btrfs.subvolume_create var dest=/mnt
salt '*' btrfs.subvolume_create var qgroupids='[200]'
'''
if qgroupids and type(qgroupids) is not list:
raise CommandExecutionError('Qgroupids parameter must be a list')
if dest:
name = os.path.join(dest, name)
# If the subvolume is there, we are done
if subvolume_exists(name):
return False
cmd = ['btrfs', 'subvolume', 'create']
if type(qgroupids) is list:
cmd.append('-i')
cmd.extend(qgroupids)
cmd.append(name)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | python | def subvolume_create(name, dest=None, qgroupids=None):
'''
Create subvolume `name` in `dest`.
Return True if the subvolume is created, False is the subvolume is
already there.
name
Name of the new subvolume
dest
If not given, the subvolume will be created in the current
directory, if given will be in /dest/name
qgroupids
Add the newly created subcolume to a qgroup. This parameter
is a list
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_create var
salt '*' btrfs.subvolume_create var dest=/mnt
salt '*' btrfs.subvolume_create var qgroupids='[200]'
'''
if qgroupids and type(qgroupids) is not list:
raise CommandExecutionError('Qgroupids parameter must be a list')
if dest:
name = os.path.join(dest, name)
# If the subvolume is there, we are done
if subvolume_exists(name):
return False
cmd = ['btrfs', 'subvolume', 'create']
if type(qgroupids) is list:
cmd.append('-i')
cmd.extend(qgroupids)
cmd.append(name)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | [
"def",
"subvolume_create",
"(",
"name",
",",
"dest",
"=",
"None",
",",
"qgroupids",
"=",
"None",
")",
":",
"if",
"qgroupids",
"and",
"type",
"(",
"qgroupids",
")",
"is",
"not",
"list",
":",
"raise",
"CommandExecutionError",
"(",
"'Qgroupids parameter must be a... | Create subvolume `name` in `dest`.
Return True if the subvolume is created, False is the subvolume is
already there.
name
Name of the new subvolume
dest
If not given, the subvolume will be created in the current
directory, if given will be in /dest/name
qgroupids
Add the newly created subcolume to a qgroup. This parameter
is a list
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_create var
salt '*' btrfs.subvolume_create var dest=/mnt
salt '*' btrfs.subvolume_create var qgroupids='[200]' | [
"Create",
"subvolume",
"name",
"in",
"dest",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L696-L741 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_delete | def subvolume_delete(name=None, names=None, commit=None):
'''
Delete the subvolume(s) from the filesystem
The user can remove one single subvolume (name) or multiple of
then at the same time (names). One of the two parameters needs to
specified.
Please, refer to the documentation to understand the implication
on the transactions, and when the subvolume is really deleted.
Return True if the subvolume is deleted, False is the subvolume
was already missing.
name
Name of the subvolume to remove
names
List of names of subvolumes to remove
commit
* 'after': Wait for transaction commit at the end
* 'each': Wait for transaction commit after each delete
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_delete /var/volumes/tmp
salt '*' btrfs.subvolume_delete /var/volumes/tmp commit=after
'''
if not name and not (names and type(names) is list):
raise CommandExecutionError('Provide a value for the name parameter')
if commit and commit not in ('after', 'each'):
raise CommandExecutionError('Value for commit not recognized')
# Filter the names and take the ones that are still there
names = [n for n in itertools.chain([name], names or [])
if n and subvolume_exists(n)]
# If the subvolumes are gone, we are done
if not names:
return False
cmd = ['btrfs', 'subvolume', 'delete']
if commit == 'after':
cmd.append('--commit-after')
elif commit == 'each':
cmd.append('--commit-each')
cmd.extend(names)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | python | def subvolume_delete(name=None, names=None, commit=None):
'''
Delete the subvolume(s) from the filesystem
The user can remove one single subvolume (name) or multiple of
then at the same time (names). One of the two parameters needs to
specified.
Please, refer to the documentation to understand the implication
on the transactions, and when the subvolume is really deleted.
Return True if the subvolume is deleted, False is the subvolume
was already missing.
name
Name of the subvolume to remove
names
List of names of subvolumes to remove
commit
* 'after': Wait for transaction commit at the end
* 'each': Wait for transaction commit after each delete
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_delete /var/volumes/tmp
salt '*' btrfs.subvolume_delete /var/volumes/tmp commit=after
'''
if not name and not (names and type(names) is list):
raise CommandExecutionError('Provide a value for the name parameter')
if commit and commit not in ('after', 'each'):
raise CommandExecutionError('Value for commit not recognized')
# Filter the names and take the ones that are still there
names = [n for n in itertools.chain([name], names or [])
if n and subvolume_exists(n)]
# If the subvolumes are gone, we are done
if not names:
return False
cmd = ['btrfs', 'subvolume', 'delete']
if commit == 'after':
cmd.append('--commit-after')
elif commit == 'each':
cmd.append('--commit-each')
cmd.extend(names)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | [
"def",
"subvolume_delete",
"(",
"name",
"=",
"None",
",",
"names",
"=",
"None",
",",
"commit",
"=",
"None",
")",
":",
"if",
"not",
"name",
"and",
"not",
"(",
"names",
"and",
"type",
"(",
"names",
")",
"is",
"list",
")",
":",
"raise",
"CommandExecutio... | Delete the subvolume(s) from the filesystem
The user can remove one single subvolume (name) or multiple of
then at the same time (names). One of the two parameters needs to
specified.
Please, refer to the documentation to understand the implication
on the transactions, and when the subvolume is really deleted.
Return True if the subvolume is deleted, False is the subvolume
was already missing.
name
Name of the subvolume to remove
names
List of names of subvolumes to remove
commit
* 'after': Wait for transaction commit at the end
* 'each': Wait for transaction commit after each delete
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_delete /var/volumes/tmp
salt '*' btrfs.subvolume_delete /var/volumes/tmp commit=after | [
"Delete",
"the",
"subvolume",
"(",
"s",
")",
"from",
"the",
"filesystem"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L744-L799 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_find_new | def subvolume_find_new(name, last_gen):
'''
List the recently modified files in a subvolume
name
Name of the subvolume
last_gen
Last transid marker from where to compare
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_find_new /var/volumes/tmp 1024
'''
cmd = ['btrfs', 'subvolume', 'find-new', name, last_gen]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
lines = res['stdout'].splitlines()
# Filenames are at the end of each inode line
files = [l.split()[-1] for l in lines if l.startswith('inode')]
# The last transid is in the last line
transid = lines[-1].split()[-1]
return {
'files': files,
'transid': transid,
} | python | def subvolume_find_new(name, last_gen):
'''
List the recently modified files in a subvolume
name
Name of the subvolume
last_gen
Last transid marker from where to compare
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_find_new /var/volumes/tmp 1024
'''
cmd = ['btrfs', 'subvolume', 'find-new', name, last_gen]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
lines = res['stdout'].splitlines()
# Filenames are at the end of each inode line
files = [l.split()[-1] for l in lines if l.startswith('inode')]
# The last transid is in the last line
transid = lines[-1].split()[-1]
return {
'files': files,
'transid': transid,
} | [
"def",
"subvolume_find_new",
"(",
"name",
",",
"last_gen",
")",
":",
"cmd",
"=",
"[",
"'btrfs'",
",",
"'subvolume'",
",",
"'find-new'",
",",
"name",
",",
"last_gen",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"salt",
".",
... | List the recently modified files in a subvolume
name
Name of the subvolume
last_gen
Last transid marker from where to compare
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_find_new /var/volumes/tmp 1024 | [
"List",
"the",
"recently",
"modified",
"files",
"in",
"a",
"subvolume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L802-L832 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_get_default | def subvolume_get_default(path):
'''
Get the default subvolume of the filesystem path
path
Mount point for the subvolume
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_get_default /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'get-default', path]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
line = res['stdout'].strip()
# The ID is the second parameter, and the name the last one, or
# '(FS_TREE)'
#
# When the default one is set:
# ID 5 (FS_TREE)
#
# When we manually set a different one (var):
# ID 257 gen 8 top level 5 path var
#
id_ = line.split()[1]
name = line.split()[-1]
return {
'id': id_,
'name': name,
} | python | def subvolume_get_default(path):
'''
Get the default subvolume of the filesystem path
path
Mount point for the subvolume
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_get_default /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'get-default', path]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
line = res['stdout'].strip()
# The ID is the second parameter, and the name the last one, or
# '(FS_TREE)'
#
# When the default one is set:
# ID 5 (FS_TREE)
#
# When we manually set a different one (var):
# ID 257 gen 8 top level 5 path var
#
id_ = line.split()[1]
name = line.split()[-1]
return {
'id': id_,
'name': name,
} | [
"def",
"subvolume_get_default",
"(",
"path",
")",
":",
"cmd",
"=",
"[",
"'btrfs'",
",",
"'subvolume'",
",",
"'get-default'",
",",
"path",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
... | Get the default subvolume of the filesystem path
path
Mount point for the subvolume
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_get_default /var/volumes/tmp | [
"Get",
"the",
"default",
"subvolume",
"of",
"the",
"filesystem",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L835-L869 | train |
saltstack/salt | salt/modules/btrfs.py | _pop | def _pop(line, key, use_rest):
'''
Helper for the line parser.
If key is a prefix of line, will remove ir from the line and will
extract the value (space separation), and the rest of the line.
If use_rest is True, the value will be the rest of the line.
Return a tuple with the value and the rest of the line.
'''
value = None
if line.startswith(key):
line = line[len(key):].strip()
if use_rest:
value = line
line = ''
else:
value, line = line.split(' ', 1)
return value, line.strip() | python | def _pop(line, key, use_rest):
'''
Helper for the line parser.
If key is a prefix of line, will remove ir from the line and will
extract the value (space separation), and the rest of the line.
If use_rest is True, the value will be the rest of the line.
Return a tuple with the value and the rest of the line.
'''
value = None
if line.startswith(key):
line = line[len(key):].strip()
if use_rest:
value = line
line = ''
else:
value, line = line.split(' ', 1)
return value, line.strip() | [
"def",
"_pop",
"(",
"line",
",",
"key",
",",
"use_rest",
")",
":",
"value",
"=",
"None",
"if",
"line",
".",
"startswith",
"(",
"key",
")",
":",
"line",
"=",
"line",
"[",
"len",
"(",
"key",
")",
":",
"]",
".",
"strip",
"(",
")",
"if",
"use_rest"... | Helper for the line parser.
If key is a prefix of line, will remove ir from the line and will
extract the value (space separation), and the rest of the line.
If use_rest is True, the value will be the rest of the line.
Return a tuple with the value and the rest of the line. | [
"Helper",
"for",
"the",
"line",
"parser",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L872-L891 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_list | def subvolume_list(path, parent_id=False, absolute=False,
ogeneration=False, generation=False,
subvolumes=False, uuid=False, parent_uuid=False,
sent_subvolume_uuid=False, snapshots=False,
readonly=False, deleted=False, generation_cmp=None,
ogeneration_cmp=None, sort=None):
'''
List the subvolumes present in the filesystem.
path
Mount point for the subvolume
parent_id
Print parent ID
absolute
Print all the subvolumes in the filesystem and distinguish
between absolute and relative path with respect to the given
<path>
ogeneration
Print the ogeneration of the subvolume
generation
Print the generation of the subvolume
subvolumes
Print only subvolumes below specified <path>
uuid
Print the UUID of the subvolume
parent_uuid
Print the parent uuid of subvolumes (and snapshots)
sent_subvolume_uuid
Print the UUID of the sent subvolume, where the subvolume is
the result of a receive operation
snapshots
Only snapshot subvolumes in the filesystem will be listed
readonly
Only readonly subvolumes in the filesystem will be listed
deleted
Only deleted subvolumens that are ye not cleaned
generation_cmp
List subvolumes in the filesystem that its generation is >=,
<= or = value. '+' means >= value, '-' means <= value, If
there is neither '+' nor '-', it means = value
ogeneration_cmp
List subvolumes in the filesystem that its ogeneration is >=,
<= or = value
sort
List subvolumes in order by specified items. Possible values:
* rootid
* gen
* ogen
* path
You can add '+' or '-' in front of each items, '+' means
ascending, '-' means descending. The default is ascending. You
can combite it in a list.
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_list /var/volumes/tmp
salt '*' btrfs.subvolume_list /var/volumes/tmp path=True
salt '*' btrfs.subvolume_list /var/volumes/tmp sort='[-rootid]'
'''
if sort and type(sort) is not list:
raise CommandExecutionError('Sort parameter must be a list')
valid_sorts = [
''.join((order, attrib)) for order, attrib in itertools.product(
('-', '', '+'), ('rootid', 'gen', 'ogen', 'path'))
]
if sort and not all(s in valid_sorts for s in sort):
raise CommandExecutionError('Value for sort not recognized')
cmd = ['btrfs', 'subvolume', 'list']
params = ((parent_id, '-p'),
(absolute, '-a'),
(ogeneration, '-c'),
(generation, '-g'),
(subvolumes, '-o'),
(uuid, '-u'),
(parent_uuid, '-q'),
(sent_subvolume_uuid, '-R'),
(snapshots, '-s'),
(readonly, '-r'),
(deleted, '-d'))
cmd.extend(p[1] for p in params if p[0])
if generation_cmp:
cmd.extend(['-G', generation_cmp])
if ogeneration_cmp:
cmd.extend(['-C', ogeneration_cmp])
# We already validated the content of the list
if sort:
cmd.append('--sort={}'.format(','.join(sort)))
cmd.append(path)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
# Parse the output. ID and gen are always at the begining, and
# path is always at the end. There is only one column that
# contains space (top level), and the path value can also have
# spaces. The issue is that we do not know how many spaces do we
# have in the path name, so any classic solution based on split
# will fail.
#
# This list is in order.
columns = ('ID', 'gen', 'cgen', 'parent', 'top level', 'otime',
'parent_uuid', 'received_uuid', 'uuid', 'path')
result = []
for line in res['stdout'].splitlines():
table = {}
for key in columns:
value, line = _pop(line, key, key == 'path')
if value:
table[key.lower()] = value
# If line is not empty here, we are not able to parse it
if not line:
result.append(table)
return result | python | def subvolume_list(path, parent_id=False, absolute=False,
ogeneration=False, generation=False,
subvolumes=False, uuid=False, parent_uuid=False,
sent_subvolume_uuid=False, snapshots=False,
readonly=False, deleted=False, generation_cmp=None,
ogeneration_cmp=None, sort=None):
'''
List the subvolumes present in the filesystem.
path
Mount point for the subvolume
parent_id
Print parent ID
absolute
Print all the subvolumes in the filesystem and distinguish
between absolute and relative path with respect to the given
<path>
ogeneration
Print the ogeneration of the subvolume
generation
Print the generation of the subvolume
subvolumes
Print only subvolumes below specified <path>
uuid
Print the UUID of the subvolume
parent_uuid
Print the parent uuid of subvolumes (and snapshots)
sent_subvolume_uuid
Print the UUID of the sent subvolume, where the subvolume is
the result of a receive operation
snapshots
Only snapshot subvolumes in the filesystem will be listed
readonly
Only readonly subvolumes in the filesystem will be listed
deleted
Only deleted subvolumens that are ye not cleaned
generation_cmp
List subvolumes in the filesystem that its generation is >=,
<= or = value. '+' means >= value, '-' means <= value, If
there is neither '+' nor '-', it means = value
ogeneration_cmp
List subvolumes in the filesystem that its ogeneration is >=,
<= or = value
sort
List subvolumes in order by specified items. Possible values:
* rootid
* gen
* ogen
* path
You can add '+' or '-' in front of each items, '+' means
ascending, '-' means descending. The default is ascending. You
can combite it in a list.
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_list /var/volumes/tmp
salt '*' btrfs.subvolume_list /var/volumes/tmp path=True
salt '*' btrfs.subvolume_list /var/volumes/tmp sort='[-rootid]'
'''
if sort and type(sort) is not list:
raise CommandExecutionError('Sort parameter must be a list')
valid_sorts = [
''.join((order, attrib)) for order, attrib in itertools.product(
('-', '', '+'), ('rootid', 'gen', 'ogen', 'path'))
]
if sort and not all(s in valid_sorts for s in sort):
raise CommandExecutionError('Value for sort not recognized')
cmd = ['btrfs', 'subvolume', 'list']
params = ((parent_id, '-p'),
(absolute, '-a'),
(ogeneration, '-c'),
(generation, '-g'),
(subvolumes, '-o'),
(uuid, '-u'),
(parent_uuid, '-q'),
(sent_subvolume_uuid, '-R'),
(snapshots, '-s'),
(readonly, '-r'),
(deleted, '-d'))
cmd.extend(p[1] for p in params if p[0])
if generation_cmp:
cmd.extend(['-G', generation_cmp])
if ogeneration_cmp:
cmd.extend(['-C', ogeneration_cmp])
# We already validated the content of the list
if sort:
cmd.append('--sort={}'.format(','.join(sort)))
cmd.append(path)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
# Parse the output. ID and gen are always at the begining, and
# path is always at the end. There is only one column that
# contains space (top level), and the path value can also have
# spaces. The issue is that we do not know how many spaces do we
# have in the path name, so any classic solution based on split
# will fail.
#
# This list is in order.
columns = ('ID', 'gen', 'cgen', 'parent', 'top level', 'otime',
'parent_uuid', 'received_uuid', 'uuid', 'path')
result = []
for line in res['stdout'].splitlines():
table = {}
for key in columns:
value, line = _pop(line, key, key == 'path')
if value:
table[key.lower()] = value
# If line is not empty here, we are not able to parse it
if not line:
result.append(table)
return result | [
"def",
"subvolume_list",
"(",
"path",
",",
"parent_id",
"=",
"False",
",",
"absolute",
"=",
"False",
",",
"ogeneration",
"=",
"False",
",",
"generation",
"=",
"False",
",",
"subvolumes",
"=",
"False",
",",
"uuid",
"=",
"False",
",",
"parent_uuid",
"=",
"... | List the subvolumes present in the filesystem.
path
Mount point for the subvolume
parent_id
Print parent ID
absolute
Print all the subvolumes in the filesystem and distinguish
between absolute and relative path with respect to the given
<path>
ogeneration
Print the ogeneration of the subvolume
generation
Print the generation of the subvolume
subvolumes
Print only subvolumes below specified <path>
uuid
Print the UUID of the subvolume
parent_uuid
Print the parent uuid of subvolumes (and snapshots)
sent_subvolume_uuid
Print the UUID of the sent subvolume, where the subvolume is
the result of a receive operation
snapshots
Only snapshot subvolumes in the filesystem will be listed
readonly
Only readonly subvolumes in the filesystem will be listed
deleted
Only deleted subvolumens that are ye not cleaned
generation_cmp
List subvolumes in the filesystem that its generation is >=,
<= or = value. '+' means >= value, '-' means <= value, If
there is neither '+' nor '-', it means = value
ogeneration_cmp
List subvolumes in the filesystem that its ogeneration is >=,
<= or = value
sort
List subvolumes in order by specified items. Possible values:
* rootid
* gen
* ogen
* path
You can add '+' or '-' in front of each items, '+' means
ascending, '-' means descending. The default is ascending. You
can combite it in a list.
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_list /var/volumes/tmp
salt '*' btrfs.subvolume_list /var/volumes/tmp path=True
salt '*' btrfs.subvolume_list /var/volumes/tmp sort='[-rootid]' | [
"List",
"the",
"subvolumes",
"present",
"in",
"the",
"filesystem",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L894-L1031 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_set_default | def subvolume_set_default(subvolid, path):
'''
Set the subvolume as default
subvolid
ID of the new default subvolume
path
Mount point for the filesystem
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_set_default 257 /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'set-default', subvolid, path]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | python | def subvolume_set_default(subvolid, path):
'''
Set the subvolume as default
subvolid
ID of the new default subvolume
path
Mount point for the filesystem
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_set_default 257 /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'set-default', subvolid, path]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | [
"def",
"subvolume_set_default",
"(",
"subvolid",
",",
"path",
")",
":",
"cmd",
"=",
"[",
"'btrfs'",
",",
"'subvolume'",
",",
"'set-default'",
",",
"subvolid",
",",
"path",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"salt",
"... | Set the subvolume as default
subvolid
ID of the new default subvolume
path
Mount point for the filesystem
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_set_default 257 /var/volumes/tmp | [
"Set",
"the",
"subvolume",
"as",
"default"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L1034-L1055 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_show | def subvolume_show(path):
'''
Show information of a given subvolume
path
Mount point for the filesystem
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_show /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'show', path]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
result = {}
table = {}
# The real name is the first line, later there is a table of
# values separated with colon.
stdout = res['stdout'].splitlines()
key = stdout.pop(0)
result[key.strip()] = table
for line in stdout:
key, value = line.split(':', 1)
table[key.lower().strip()] = value.strip()
return result | python | def subvolume_show(path):
'''
Show information of a given subvolume
path
Mount point for the filesystem
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_show /var/volumes/tmp
'''
cmd = ['btrfs', 'subvolume', 'show', path]
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
result = {}
table = {}
# The real name is the first line, later there is a table of
# values separated with colon.
stdout = res['stdout'].splitlines()
key = stdout.pop(0)
result[key.strip()] = table
for line in stdout:
key, value = line.split(':', 1)
table[key.lower().strip()] = value.strip()
return result | [
"def",
"subvolume_show",
"(",
"path",
")",
":",
"cmd",
"=",
"[",
"'btrfs'",
",",
"'subvolume'",
",",
"'show'",
",",
"path",
"]",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
")",
"salt",
".",
"utils",
".",
"fsutils",
".",
"_verify_run... | Show information of a given subvolume
path
Mount point for the filesystem
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_show /var/volumes/tmp | [
"Show",
"information",
"of",
"a",
"given",
"subvolume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L1058-L1088 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_snapshot | def subvolume_snapshot(source, dest=None, name=None, read_only=False):
'''
Create a snapshot of a source subvolume
source
Source subvolume from where to create the snapshot
dest
If only dest is given, the subvolume will be named as the
basename of the source
name
Name of the snapshot
read_only
Create a read only snapshot
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_snapshot /var/volumes/tmp dest=/.snapshots
salt '*' btrfs.subvolume_snapshot /var/volumes/tmp name=backup
'''
if not dest and not name:
raise CommandExecutionError('Provide parameter dest, name, or both')
cmd = ['btrfs', 'subvolume', 'snapshot']
if read_only:
cmd.append('-r')
if dest and not name:
cmd.append(dest)
if dest and name:
name = os.path.join(dest, name)
if name:
cmd.append(name)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | python | def subvolume_snapshot(source, dest=None, name=None, read_only=False):
'''
Create a snapshot of a source subvolume
source
Source subvolume from where to create the snapshot
dest
If only dest is given, the subvolume will be named as the
basename of the source
name
Name of the snapshot
read_only
Create a read only snapshot
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_snapshot /var/volumes/tmp dest=/.snapshots
salt '*' btrfs.subvolume_snapshot /var/volumes/tmp name=backup
'''
if not dest and not name:
raise CommandExecutionError('Provide parameter dest, name, or both')
cmd = ['btrfs', 'subvolume', 'snapshot']
if read_only:
cmd.append('-r')
if dest and not name:
cmd.append(dest)
if dest and name:
name = os.path.join(dest, name)
if name:
cmd.append(name)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | [
"def",
"subvolume_snapshot",
"(",
"source",
",",
"dest",
"=",
"None",
",",
"name",
"=",
"None",
",",
"read_only",
"=",
"False",
")",
":",
"if",
"not",
"dest",
"and",
"not",
"name",
":",
"raise",
"CommandExecutionError",
"(",
"'Provide parameter dest, name, or ... | Create a snapshot of a source subvolume
source
Source subvolume from where to create the snapshot
dest
If only dest is given, the subvolume will be named as the
basename of the source
name
Name of the snapshot
read_only
Create a read only snapshot
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_snapshot /var/volumes/tmp dest=/.snapshots
salt '*' btrfs.subvolume_snapshot /var/volumes/tmp name=backup | [
"Create",
"a",
"snapshot",
"of",
"a",
"source",
"subvolume"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L1091-L1131 | train |
saltstack/salt | salt/modules/btrfs.py | subvolume_sync | def subvolume_sync(path, subvolids=None, sleep=None):
'''
Wait until given subvolume are completely removed from the
filesystem after deletion.
path
Mount point for the filesystem
subvolids
List of IDs of subvolumes to wait for
sleep
Sleep N seconds betwenn checks (default: 1)
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_sync /var/volumes/tmp
salt '*' btrfs.subvolume_sync /var/volumes/tmp subvolids='[257]'
'''
if subvolids and type(subvolids) is not list:
raise CommandExecutionError('Subvolids parameter must be a list')
cmd = ['btrfs', 'subvolume', 'sync']
if sleep:
cmd.extend(['-s', sleep])
cmd.append(path)
if subvolids:
cmd.extend(subvolids)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | python | def subvolume_sync(path, subvolids=None, sleep=None):
'''
Wait until given subvolume are completely removed from the
filesystem after deletion.
path
Mount point for the filesystem
subvolids
List of IDs of subvolumes to wait for
sleep
Sleep N seconds betwenn checks (default: 1)
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_sync /var/volumes/tmp
salt '*' btrfs.subvolume_sync /var/volumes/tmp subvolids='[257]'
'''
if subvolids and type(subvolids) is not list:
raise CommandExecutionError('Subvolids parameter must be a list')
cmd = ['btrfs', 'subvolume', 'sync']
if sleep:
cmd.extend(['-s', sleep])
cmd.append(path)
if subvolids:
cmd.extend(subvolids)
res = __salt__['cmd.run_all'](cmd)
salt.utils.fsutils._verify_run(res)
return True | [
"def",
"subvolume_sync",
"(",
"path",
",",
"subvolids",
"=",
"None",
",",
"sleep",
"=",
"None",
")",
":",
"if",
"subvolids",
"and",
"type",
"(",
"subvolids",
")",
"is",
"not",
"list",
":",
"raise",
"CommandExecutionError",
"(",
"'Subvolids parameter must be a ... | Wait until given subvolume are completely removed from the
filesystem after deletion.
path
Mount point for the filesystem
subvolids
List of IDs of subvolumes to wait for
sleep
Sleep N seconds betwenn checks (default: 1)
CLI Example:
.. code-block:: bash
salt '*' btrfs.subvolume_sync /var/volumes/tmp
salt '*' btrfs.subvolume_sync /var/volumes/tmp subvolids='[257]' | [
"Wait",
"until",
"given",
"subvolume",
"are",
"completely",
"removed",
"from",
"the",
"filesystem",
"after",
"deletion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/btrfs.py#L1134-L1169 | train |
saltstack/salt | salt/modules/win_useradd.py | add | def add(name,
password=None,
fullname=None,
description=None,
groups=None,
home=None,
homedrive=None,
profile=None,
logonscript=None):
'''
Add a user to the minion.
Args:
name (str): User name
password (str, optional): User's password in plain text.
fullname (str, optional): The user's full name.
description (str, optional): A brief description of the user account.
groups (str, optional): A list of groups to add the user to.
(see chgroups)
home (str, optional): The path to the user's home directory.
homedrive (str, optional): The drive letter to assign to the home
directory. Must be the Drive Letter followed by a colon. ie: U:
profile (str, optional): An explicit path to a profile. Can be a UNC or
a folder on the system. If left blank, windows uses it's default
profile directory.
logonscript (str, optional): Path to a login script to run when the user
logs on.
Returns:
bool: True if successful. False is unsuccessful.
CLI Example:
.. code-block:: bash
salt '*' user.add name password
'''
if six.PY2:
name = _to_unicode(name)
password = _to_unicode(password)
fullname = _to_unicode(fullname)
description = _to_unicode(description)
home = _to_unicode(home)
homedrive = _to_unicode(homedrive)
profile = _to_unicode(profile)
logonscript = _to_unicode(logonscript)
user_info = {}
if name:
user_info['name'] = name
else:
return False
user_info['password'] = password
user_info['priv'] = win32netcon.USER_PRIV_USER
user_info['home_dir'] = home
user_info['comment'] = description
user_info['flags'] = win32netcon.UF_SCRIPT
user_info['script_path'] = logonscript
try:
win32net.NetUserAdd(None, 1, user_info)
except win32net.error as exc:
log.error('Failed to create user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
update(name=name,
homedrive=homedrive,
profile=profile,
fullname=fullname)
ret = chgroups(name, groups) if groups else True
return ret | python | def add(name,
password=None,
fullname=None,
description=None,
groups=None,
home=None,
homedrive=None,
profile=None,
logonscript=None):
'''
Add a user to the minion.
Args:
name (str): User name
password (str, optional): User's password in plain text.
fullname (str, optional): The user's full name.
description (str, optional): A brief description of the user account.
groups (str, optional): A list of groups to add the user to.
(see chgroups)
home (str, optional): The path to the user's home directory.
homedrive (str, optional): The drive letter to assign to the home
directory. Must be the Drive Letter followed by a colon. ie: U:
profile (str, optional): An explicit path to a profile. Can be a UNC or
a folder on the system. If left blank, windows uses it's default
profile directory.
logonscript (str, optional): Path to a login script to run when the user
logs on.
Returns:
bool: True if successful. False is unsuccessful.
CLI Example:
.. code-block:: bash
salt '*' user.add name password
'''
if six.PY2:
name = _to_unicode(name)
password = _to_unicode(password)
fullname = _to_unicode(fullname)
description = _to_unicode(description)
home = _to_unicode(home)
homedrive = _to_unicode(homedrive)
profile = _to_unicode(profile)
logonscript = _to_unicode(logonscript)
user_info = {}
if name:
user_info['name'] = name
else:
return False
user_info['password'] = password
user_info['priv'] = win32netcon.USER_PRIV_USER
user_info['home_dir'] = home
user_info['comment'] = description
user_info['flags'] = win32netcon.UF_SCRIPT
user_info['script_path'] = logonscript
try:
win32net.NetUserAdd(None, 1, user_info)
except win32net.error as exc:
log.error('Failed to create user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
update(name=name,
homedrive=homedrive,
profile=profile,
fullname=fullname)
ret = chgroups(name, groups) if groups else True
return ret | [
"def",
"add",
"(",
"name",
",",
"password",
"=",
"None",
",",
"fullname",
"=",
"None",
",",
"description",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"home",
"=",
"None",
",",
"homedrive",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"logonscrip... | Add a user to the minion.
Args:
name (str): User name
password (str, optional): User's password in plain text.
fullname (str, optional): The user's full name.
description (str, optional): A brief description of the user account.
groups (str, optional): A list of groups to add the user to.
(see chgroups)
home (str, optional): The path to the user's home directory.
homedrive (str, optional): The drive letter to assign to the home
directory. Must be the Drive Letter followed by a colon. ie: U:
profile (str, optional): An explicit path to a profile. Can be a UNC or
a folder on the system. If left blank, windows uses it's default
profile directory.
logonscript (str, optional): Path to a login script to run when the user
logs on.
Returns:
bool: True if successful. False is unsuccessful.
CLI Example:
.. code-block:: bash
salt '*' user.add name password | [
"Add",
"a",
"user",
"to",
"the",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L99-L182 | train |
saltstack/salt | salt/modules/win_useradd.py | update | def update(name,
password=None,
fullname=None,
description=None,
home=None,
homedrive=None,
logonscript=None,
profile=None,
expiration_date=None,
expired=None,
account_disabled=None,
unlock_account=None,
password_never_expires=None,
disallow_change_password=None):
# pylint: disable=anomalous-backslash-in-string
'''
Updates settings for the windows user. Name is the only required parameter.
Settings will only be changed if the parameter is passed a value.
.. versionadded:: 2015.8.0
Args:
name (str): The user name to update.
password (str, optional): New user password in plain text.
fullname (str, optional): The user's full name.
description (str, optional): A brief description of the user account.
home (str, optional): The path to the user's home directory.
homedrive (str, optional): The drive letter to assign to the home
directory. Must be the Drive Letter followed by a colon. ie: U:
logonscript (str, optional): The path to the logon script.
profile (str, optional): The path to the user's profile directory.
expiration_date (date, optional): The date and time when the account
expires. Can be a valid date/time string. To set to never expire
pass the string 'Never'.
expired (bool, optional): Pass `True` to expire the account. The user
will be prompted to change their password at the next logon. Pass
`False` to mark the account as 'not expired'. You can't use this to
negate the expiration if the expiration was caused by the account
expiring. You'll have to change the `expiration_date` as well.
account_disabled (bool, optional): True disables the account. False
enables the account.
unlock_account (bool, optional): True unlocks a locked user account.
False is ignored.
password_never_expires (bool, optional): True sets the password to never
expire. False allows the password to expire.
disallow_change_password (bool, optional): True blocks the user from
changing the password. False allows the user to change the password.
Returns:
bool: True if successful. False is unsuccessful.
CLI Example:
.. code-block:: bash
salt '*' user.update bob password=secret profile=C:\\Users\\Bob
home=\\server\homeshare\bob homedrive=U:
'''
# pylint: enable=anomalous-backslash-in-string
if six.PY2:
name = _to_unicode(name)
password = _to_unicode(password)
fullname = _to_unicode(fullname)
description = _to_unicode(description)
home = _to_unicode(home)
homedrive = _to_unicode(homedrive)
logonscript = _to_unicode(logonscript)
profile = _to_unicode(profile)
# Make sure the user exists
# Return an object containing current settings for the user
try:
user_info = win32net.NetUserGetInfo(None, name, 4)
except win32net.error as exc:
log.error('Failed to update user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
# Check parameters to update
# Update the user object with new settings
if password:
user_info['password'] = password
if home:
user_info['home_dir'] = home
if homedrive:
user_info['home_dir_drive'] = homedrive
if description:
user_info['comment'] = description
if logonscript:
user_info['script_path'] = logonscript
if fullname:
user_info['full_name'] = fullname
if profile:
user_info['profile'] = profile
if expiration_date:
if expiration_date == 'Never':
user_info['acct_expires'] = win32netcon.TIMEQ_FOREVER
else:
try:
dt_obj = salt.utils.dateutils.date_cast(expiration_date)
except (ValueError, RuntimeError):
return 'Invalid Date/Time Format: {0}'.format(expiration_date)
user_info['acct_expires'] = time.mktime(dt_obj.timetuple())
if expired is not None:
if expired:
user_info['password_expired'] = 1
else:
user_info['password_expired'] = 0
if account_disabled is not None:
if account_disabled:
user_info['flags'] |= win32netcon.UF_ACCOUNTDISABLE
else:
user_info['flags'] &= ~win32netcon.UF_ACCOUNTDISABLE
if unlock_account is not None:
if unlock_account:
user_info['flags'] &= ~win32netcon.UF_LOCKOUT
if password_never_expires is not None:
if password_never_expires:
user_info['flags'] |= win32netcon.UF_DONT_EXPIRE_PASSWD
else:
user_info['flags'] &= ~win32netcon.UF_DONT_EXPIRE_PASSWD
if disallow_change_password is not None:
if disallow_change_password:
user_info['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE
else:
user_info['flags'] &= ~win32netcon.UF_PASSWD_CANT_CHANGE
# Apply new settings
try:
win32net.NetUserSetInfo(None, name, 4, user_info)
except win32net.error as exc:
log.error('Failed to update user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
return True | python | def update(name,
password=None,
fullname=None,
description=None,
home=None,
homedrive=None,
logonscript=None,
profile=None,
expiration_date=None,
expired=None,
account_disabled=None,
unlock_account=None,
password_never_expires=None,
disallow_change_password=None):
# pylint: disable=anomalous-backslash-in-string
'''
Updates settings for the windows user. Name is the only required parameter.
Settings will only be changed if the parameter is passed a value.
.. versionadded:: 2015.8.0
Args:
name (str): The user name to update.
password (str, optional): New user password in plain text.
fullname (str, optional): The user's full name.
description (str, optional): A brief description of the user account.
home (str, optional): The path to the user's home directory.
homedrive (str, optional): The drive letter to assign to the home
directory. Must be the Drive Letter followed by a colon. ie: U:
logonscript (str, optional): The path to the logon script.
profile (str, optional): The path to the user's profile directory.
expiration_date (date, optional): The date and time when the account
expires. Can be a valid date/time string. To set to never expire
pass the string 'Never'.
expired (bool, optional): Pass `True` to expire the account. The user
will be prompted to change their password at the next logon. Pass
`False` to mark the account as 'not expired'. You can't use this to
negate the expiration if the expiration was caused by the account
expiring. You'll have to change the `expiration_date` as well.
account_disabled (bool, optional): True disables the account. False
enables the account.
unlock_account (bool, optional): True unlocks a locked user account.
False is ignored.
password_never_expires (bool, optional): True sets the password to never
expire. False allows the password to expire.
disallow_change_password (bool, optional): True blocks the user from
changing the password. False allows the user to change the password.
Returns:
bool: True if successful. False is unsuccessful.
CLI Example:
.. code-block:: bash
salt '*' user.update bob password=secret profile=C:\\Users\\Bob
home=\\server\homeshare\bob homedrive=U:
'''
# pylint: enable=anomalous-backslash-in-string
if six.PY2:
name = _to_unicode(name)
password = _to_unicode(password)
fullname = _to_unicode(fullname)
description = _to_unicode(description)
home = _to_unicode(home)
homedrive = _to_unicode(homedrive)
logonscript = _to_unicode(logonscript)
profile = _to_unicode(profile)
# Make sure the user exists
# Return an object containing current settings for the user
try:
user_info = win32net.NetUserGetInfo(None, name, 4)
except win32net.error as exc:
log.error('Failed to update user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
# Check parameters to update
# Update the user object with new settings
if password:
user_info['password'] = password
if home:
user_info['home_dir'] = home
if homedrive:
user_info['home_dir_drive'] = homedrive
if description:
user_info['comment'] = description
if logonscript:
user_info['script_path'] = logonscript
if fullname:
user_info['full_name'] = fullname
if profile:
user_info['profile'] = profile
if expiration_date:
if expiration_date == 'Never':
user_info['acct_expires'] = win32netcon.TIMEQ_FOREVER
else:
try:
dt_obj = salt.utils.dateutils.date_cast(expiration_date)
except (ValueError, RuntimeError):
return 'Invalid Date/Time Format: {0}'.format(expiration_date)
user_info['acct_expires'] = time.mktime(dt_obj.timetuple())
if expired is not None:
if expired:
user_info['password_expired'] = 1
else:
user_info['password_expired'] = 0
if account_disabled is not None:
if account_disabled:
user_info['flags'] |= win32netcon.UF_ACCOUNTDISABLE
else:
user_info['flags'] &= ~win32netcon.UF_ACCOUNTDISABLE
if unlock_account is not None:
if unlock_account:
user_info['flags'] &= ~win32netcon.UF_LOCKOUT
if password_never_expires is not None:
if password_never_expires:
user_info['flags'] |= win32netcon.UF_DONT_EXPIRE_PASSWD
else:
user_info['flags'] &= ~win32netcon.UF_DONT_EXPIRE_PASSWD
if disallow_change_password is not None:
if disallow_change_password:
user_info['flags'] |= win32netcon.UF_PASSWD_CANT_CHANGE
else:
user_info['flags'] &= ~win32netcon.UF_PASSWD_CANT_CHANGE
# Apply new settings
try:
win32net.NetUserSetInfo(None, name, 4, user_info)
except win32net.error as exc:
log.error('Failed to update user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
return True | [
"def",
"update",
"(",
"name",
",",
"password",
"=",
"None",
",",
"fullname",
"=",
"None",
",",
"description",
"=",
"None",
",",
"home",
"=",
"None",
",",
"homedrive",
"=",
"None",
",",
"logonscript",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"ex... | Updates settings for the windows user. Name is the only required parameter.
Settings will only be changed if the parameter is passed a value.
.. versionadded:: 2015.8.0
Args:
name (str): The user name to update.
password (str, optional): New user password in plain text.
fullname (str, optional): The user's full name.
description (str, optional): A brief description of the user account.
home (str, optional): The path to the user's home directory.
homedrive (str, optional): The drive letter to assign to the home
directory. Must be the Drive Letter followed by a colon. ie: U:
logonscript (str, optional): The path to the logon script.
profile (str, optional): The path to the user's profile directory.
expiration_date (date, optional): The date and time when the account
expires. Can be a valid date/time string. To set to never expire
pass the string 'Never'.
expired (bool, optional): Pass `True` to expire the account. The user
will be prompted to change their password at the next logon. Pass
`False` to mark the account as 'not expired'. You can't use this to
negate the expiration if the expiration was caused by the account
expiring. You'll have to change the `expiration_date` as well.
account_disabled (bool, optional): True disables the account. False
enables the account.
unlock_account (bool, optional): True unlocks a locked user account.
False is ignored.
password_never_expires (bool, optional): True sets the password to never
expire. False allows the password to expire.
disallow_change_password (bool, optional): True blocks the user from
changing the password. False allows the user to change the password.
Returns:
bool: True if successful. False is unsuccessful.
CLI Example:
.. code-block:: bash
salt '*' user.update bob password=secret profile=C:\\Users\\Bob
home=\\server\homeshare\bob homedrive=U: | [
"Updates",
"settings",
"for",
"the",
"windows",
"user",
".",
"Name",
"is",
"the",
"only",
"required",
"parameter",
".",
"Settings",
"will",
"only",
"be",
"changed",
"if",
"the",
"parameter",
"is",
"passed",
"a",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L185-L337 | train |
saltstack/salt | salt/modules/win_useradd.py | delete | def delete(name,
purge=False,
force=False):
'''
Remove a user from the minion
Args:
name (str): The name of the user to delete
purge (bool, optional): Boolean value indicating that the user profile
should also be removed when the user account is deleted. If set to
True the profile will be removed. Default is False.
force (bool, optional): Boolean value indicating that the user account
should be deleted even if the user is logged in. True will log the
user out and delete user.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.delete name
'''
if six.PY2:
name = _to_unicode(name)
# Check if the user exists
try:
user_info = win32net.NetUserGetInfo(None, name, 4)
except win32net.error as exc:
log.error('User not found: %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
# Check if the user is logged in
# Return a list of logged in users
try:
sess_list = win32ts.WTSEnumerateSessions()
except win32ts.error as exc:
log.error('No logged in users found')
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
# Is the user one that is logged in
logged_in = False
session_id = None
for sess in sess_list:
if win32ts.WTSQuerySessionInformation(None, sess['SessionId'], win32ts.WTSUserName) == name:
session_id = sess['SessionId']
logged_in = True
# If logged in and set to force, log the user out and continue
# If logged in and not set to force, return false
if logged_in:
if force:
try:
win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except win32ts.error as exc:
log.error('User not found: %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
else:
log.error('User %s is currently logged in.', name)
return False
# Remove the User Profile directory
if purge:
try:
sid = getUserSid(name)
win32profile.DeleteProfile(sid)
except pywintypes.error as exc:
(number, context, message) = exc.args
if number == 2: # Profile Folder Not Found
pass
else:
log.error('Failed to remove profile for %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
# And finally remove the user account
try:
win32net.NetUserDel(None, name)
except win32net.error as exc:
log.error('Failed to delete user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
return True | python | def delete(name,
purge=False,
force=False):
'''
Remove a user from the minion
Args:
name (str): The name of the user to delete
purge (bool, optional): Boolean value indicating that the user profile
should also be removed when the user account is deleted. If set to
True the profile will be removed. Default is False.
force (bool, optional): Boolean value indicating that the user account
should be deleted even if the user is logged in. True will log the
user out and delete user.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.delete name
'''
if six.PY2:
name = _to_unicode(name)
# Check if the user exists
try:
user_info = win32net.NetUserGetInfo(None, name, 4)
except win32net.error as exc:
log.error('User not found: %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
# Check if the user is logged in
# Return a list of logged in users
try:
sess_list = win32ts.WTSEnumerateSessions()
except win32ts.error as exc:
log.error('No logged in users found')
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
# Is the user one that is logged in
logged_in = False
session_id = None
for sess in sess_list:
if win32ts.WTSQuerySessionInformation(None, sess['SessionId'], win32ts.WTSUserName) == name:
session_id = sess['SessionId']
logged_in = True
# If logged in and set to force, log the user out and continue
# If logged in and not set to force, return false
if logged_in:
if force:
try:
win32ts.WTSLogoffSession(win32ts.WTS_CURRENT_SERVER_HANDLE, session_id, True)
except win32ts.error as exc:
log.error('User not found: %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
else:
log.error('User %s is currently logged in.', name)
return False
# Remove the User Profile directory
if purge:
try:
sid = getUserSid(name)
win32profile.DeleteProfile(sid)
except pywintypes.error as exc:
(number, context, message) = exc.args
if number == 2: # Profile Folder Not Found
pass
else:
log.error('Failed to remove profile for %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
# And finally remove the user account
try:
win32net.NetUserDel(None, name)
except win32net.error as exc:
log.error('Failed to delete user %s', name)
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
return False
return True | [
"def",
"delete",
"(",
"name",
",",
"purge",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"# Check if the user exists",
"try",
":",
"user_info",
"=",
"win32net",
".",
"Ne... | Remove a user from the minion
Args:
name (str): The name of the user to delete
purge (bool, optional): Boolean value indicating that the user profile
should also be removed when the user account is deleted. If set to
True the profile will be removed. Default is False.
force (bool, optional): Boolean value indicating that the user account
should be deleted even if the user is logged in. True will log the
user out and delete user.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.delete name | [
"Remove",
"a",
"user",
"from",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L340-L439 | train |
saltstack/salt | salt/modules/win_useradd.py | getUserSid | def getUserSid(username):
'''
Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy
'''
if six.PY2:
username = _to_unicode(username)
domain = win32api.GetComputerName()
if username.find('\\') != -1:
domain = username.split('\\')[0]
username = username.split('\\')[-1]
domain = domain.upper()
return win32security.ConvertSidToStringSid(
win32security.LookupAccountName(None, domain + '\\' + username)[0]) | python | def getUserSid(username):
'''
Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy
'''
if six.PY2:
username = _to_unicode(username)
domain = win32api.GetComputerName()
if username.find('\\') != -1:
domain = username.split('\\')[0]
username = username.split('\\')[-1]
domain = domain.upper()
return win32security.ConvertSidToStringSid(
win32security.LookupAccountName(None, domain + '\\' + username)[0]) | [
"def",
"getUserSid",
"(",
"username",
")",
":",
"if",
"six",
".",
"PY2",
":",
"username",
"=",
"_to_unicode",
"(",
"username",
")",
"domain",
"=",
"win32api",
".",
"GetComputerName",
"(",
")",
"if",
"username",
".",
"find",
"(",
"'\\\\'",
")",
"!=",
"-... | Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy | [
"Get",
"the",
"Security",
"ID",
"for",
"the",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L442-L467 | train |
saltstack/salt | salt/modules/win_useradd.py | addgroup | def addgroup(name, group):
'''
Add user to a group
Args:
name (str): The user name to add to the group
group (str): The name of the group to which to add the user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.addgroup jsnuffy 'Power Users'
'''
if six.PY2:
name = _to_unicode(name)
group = _to_unicode(group)
name = _cmd_quote(name)
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
user = info(name)
if not user:
return False
if group in user['groups']:
return True
cmd = 'net localgroup "{0}" {1} /add'.format(group, name)
ret = __salt__['cmd.run_all'](cmd, python_shell=True)
return ret['retcode'] == 0 | python | def addgroup(name, group):
'''
Add user to a group
Args:
name (str): The user name to add to the group
group (str): The name of the group to which to add the user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.addgroup jsnuffy 'Power Users'
'''
if six.PY2:
name = _to_unicode(name)
group = _to_unicode(group)
name = _cmd_quote(name)
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
user = info(name)
if not user:
return False
if group in user['groups']:
return True
cmd = 'net localgroup "{0}" {1} /add'.format(group, name)
ret = __salt__['cmd.run_all'](cmd, python_shell=True)
return ret['retcode'] == 0 | [
"def",
"addgroup",
"(",
"name",
",",
"group",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"group",
"=",
"_to_unicode",
"(",
"group",
")",
"name",
"=",
"_cmd_quote",
"(",
"name",
")",
"group",
"=",
"_cmd_quote... | Add user to a group
Args:
name (str): The user name to add to the group
group (str): The name of the group to which to add the user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.addgroup jsnuffy 'Power Users' | [
"Add",
"user",
"to",
"a",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L491-L525 | train |
saltstack/salt | salt/modules/win_useradd.py | chhome | def chhome(name, home, **kwargs):
'''
Change the home directory of the user, pass True for persist to move files
to the new home directory if the old home directory exist.
Args:
name (str): The name of the user whose home directory you wish to change
home (str): The new location of the home directory
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo \\\\fileserver\\home\\foo True
'''
if six.PY2:
name = _to_unicode(name)
home = _to_unicode(home)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
persist = kwargs.pop('persist', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if persist:
log.info('Ignoring unsupported \'persist\' argument to user.chhome')
pre_info = info(name)
if not pre_info:
return False
if home == pre_info['home']:
return True
if not update(name=name, home=home):
return False
post_info = info(name)
if post_info['home'] != pre_info['home']:
return post_info['home'] == home
return False | python | def chhome(name, home, **kwargs):
'''
Change the home directory of the user, pass True for persist to move files
to the new home directory if the old home directory exist.
Args:
name (str): The name of the user whose home directory you wish to change
home (str): The new location of the home directory
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo \\\\fileserver\\home\\foo True
'''
if six.PY2:
name = _to_unicode(name)
home = _to_unicode(home)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
persist = kwargs.pop('persist', False)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
if persist:
log.info('Ignoring unsupported \'persist\' argument to user.chhome')
pre_info = info(name)
if not pre_info:
return False
if home == pre_info['home']:
return True
if not update(name=name, home=home):
return False
post_info = info(name)
if post_info['home'] != pre_info['home']:
return post_info['home'] == home
return False | [
"def",
"chhome",
"(",
"name",
",",
"home",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"home",
"=",
"_to_unicode",
"(",
"home",
")",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"arg... | Change the home directory of the user, pass True for persist to move files
to the new home directory if the old home directory exist.
Args:
name (str): The name of the user whose home directory you wish to change
home (str): The new location of the home directory
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo \\\\fileserver\\home\\foo True | [
"Change",
"the",
"home",
"directory",
"of",
"the",
"user",
"pass",
"True",
"for",
"persist",
"to",
"move",
"files",
"to",
"the",
"new",
"home",
"directory",
"if",
"the",
"old",
"home",
"directory",
"exist",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L567-L612 | train |
saltstack/salt | salt/modules/win_useradd.py | chgroups | def chgroups(name, groups, append=True):
'''
Change the groups this user belongs to, add append=False to make the user a
member of only the specified groups
Args:
name (str): The user name for which to change groups
groups (str, list): A single group or a list of groups to assign to the
user. For multiple groups this can be a comma delimited string or a
list.
append (bool, optional): True adds the passed groups to the user's
current groups. False sets the user's groups to the passed groups
only. Default is True.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chgroups jsnuffy Administrators,Users True
'''
if six.PY2:
name = _to_unicode(name)
if isinstance(groups, string_types):
groups = groups.split(',')
groups = [x.strip(' *') for x in groups]
if six.PY2:
groups = [_to_unicode(x) for x in groups]
ugrps = set(list_groups(name))
if ugrps == set(groups):
return True
name = _cmd_quote(name)
if not append:
for group in ugrps:
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
if group not in groups:
cmd = 'net localgroup "{0}" {1} /delete'.format(group, name)
__salt__['cmd.run_all'](cmd, python_shell=True)
for group in groups:
if group in ugrps:
continue
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
cmd = 'net localgroup "{0}" {1} /add'.format(group, name)
out = __salt__['cmd.run_all'](cmd, python_shell=True)
if out['retcode'] != 0:
log.error(out['stdout'])
return False
agrps = set(list_groups(name))
return len(ugrps - agrps) == 0 | python | def chgroups(name, groups, append=True):
'''
Change the groups this user belongs to, add append=False to make the user a
member of only the specified groups
Args:
name (str): The user name for which to change groups
groups (str, list): A single group or a list of groups to assign to the
user. For multiple groups this can be a comma delimited string or a
list.
append (bool, optional): True adds the passed groups to the user's
current groups. False sets the user's groups to the passed groups
only. Default is True.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chgroups jsnuffy Administrators,Users True
'''
if six.PY2:
name = _to_unicode(name)
if isinstance(groups, string_types):
groups = groups.split(',')
groups = [x.strip(' *') for x in groups]
if six.PY2:
groups = [_to_unicode(x) for x in groups]
ugrps = set(list_groups(name))
if ugrps == set(groups):
return True
name = _cmd_quote(name)
if not append:
for group in ugrps:
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
if group not in groups:
cmd = 'net localgroup "{0}" {1} /delete'.format(group, name)
__salt__['cmd.run_all'](cmd, python_shell=True)
for group in groups:
if group in ugrps:
continue
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
cmd = 'net localgroup "{0}" {1} /add'.format(group, name)
out = __salt__['cmd.run_all'](cmd, python_shell=True)
if out['retcode'] != 0:
log.error(out['stdout'])
return False
agrps = set(list_groups(name))
return len(ugrps - agrps) == 0 | [
"def",
"chgroups",
"(",
"name",
",",
"groups",
",",
"append",
"=",
"True",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"if",
"isinstance",
"(",
"groups",
",",
"string_types",
")",
":",
"groups",
"=",
"groups"... | Change the groups this user belongs to, add append=False to make the user a
member of only the specified groups
Args:
name (str): The user name for which to change groups
groups (str, list): A single group or a list of groups to assign to the
user. For multiple groups this can be a comma delimited string or a
list.
append (bool, optional): True adds the passed groups to the user's
current groups. False sets the user's groups to the passed groups
only. Default is True.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chgroups jsnuffy Administrators,Users True | [
"Change",
"the",
"groups",
"this",
"user",
"belongs",
"to",
"add",
"append",
"=",
"False",
"to",
"make",
"the",
"user",
"a",
"member",
"of",
"only",
"the",
"specified",
"groups"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L657-L716 | train |
saltstack/salt | salt/modules/win_useradd.py | info | def info(name):
'''
Return user information
Args:
name (str): Username for which to display information
Returns:
dict: A dictionary containing user information
- fullname
- username
- SID
- passwd (will always return None)
- comment (same as description, left here for backwards compatibility)
- description
- active
- logonscript
- profile
- home
- homedrive
- groups
- password_changed
- successful_logon_attempts
- failed_logon_attempts
- last_logon
- account_disabled
- account_locked
- password_never_expires
- disallow_change_password
- gid
CLI Example:
.. code-block:: bash
salt '*' user.info jsnuffy
'''
if six.PY2:
name = _to_unicode(name)
ret = {}
items = {}
try:
items = win32net.NetUserGetInfo(None, name, 4)
except win32net.error:
pass
if items:
groups = []
try:
groups = win32net.NetUserGetLocalGroups(None, name)
except win32net.error:
pass
ret['fullname'] = items['full_name']
ret['name'] = items['name']
ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid'])
ret['passwd'] = items['password']
ret['comment'] = items['comment']
ret['description'] = items['comment']
ret['active'] = (not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE))
ret['logonscript'] = items['script_path']
ret['profile'] = items['profile']
ret['failed_logon_attempts'] = items['bad_pw_count']
ret['successful_logon_attempts'] = items['num_logons']
secs = time.mktime(datetime.now().timetuple()) - items['password_age']
ret['password_changed'] = datetime.fromtimestamp(secs). \
strftime('%Y-%m-%d %H:%M:%S')
if items['last_logon'] == 0:
ret['last_logon'] = 'Never'
else:
ret['last_logon'] = datetime.fromtimestamp(items['last_logon']).\
strftime('%Y-%m-%d %H:%M:%S')
ret['expiration_date'] = datetime.fromtimestamp(items['acct_expires']).\
strftime('%Y-%m-%d %H:%M:%S')
ret['expired'] = items['password_expired'] == 1
if not ret['profile']:
ret['profile'] = _get_userprofile_from_registry(name, ret['uid'])
ret['home'] = items['home_dir']
ret['homedrive'] = items['home_dir_drive']
if not ret['home']:
ret['home'] = ret['profile']
ret['groups'] = groups
if items['flags'] & win32netcon.UF_DONT_EXPIRE_PASSWD == 0:
ret['password_never_expires'] = False
else:
ret['password_never_expires'] = True
if items['flags'] & win32netcon.UF_ACCOUNTDISABLE == 0:
ret['account_disabled'] = False
else:
ret['account_disabled'] = True
if items['flags'] & win32netcon.UF_LOCKOUT == 0:
ret['account_locked'] = False
else:
ret['account_locked'] = True
if items['flags'] & win32netcon.UF_PASSWD_CANT_CHANGE == 0:
ret['disallow_change_password'] = False
else:
ret['disallow_change_password'] = True
ret['gid'] = ''
return ret
else:
return {} | python | def info(name):
'''
Return user information
Args:
name (str): Username for which to display information
Returns:
dict: A dictionary containing user information
- fullname
- username
- SID
- passwd (will always return None)
- comment (same as description, left here for backwards compatibility)
- description
- active
- logonscript
- profile
- home
- homedrive
- groups
- password_changed
- successful_logon_attempts
- failed_logon_attempts
- last_logon
- account_disabled
- account_locked
- password_never_expires
- disallow_change_password
- gid
CLI Example:
.. code-block:: bash
salt '*' user.info jsnuffy
'''
if six.PY2:
name = _to_unicode(name)
ret = {}
items = {}
try:
items = win32net.NetUserGetInfo(None, name, 4)
except win32net.error:
pass
if items:
groups = []
try:
groups = win32net.NetUserGetLocalGroups(None, name)
except win32net.error:
pass
ret['fullname'] = items['full_name']
ret['name'] = items['name']
ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid'])
ret['passwd'] = items['password']
ret['comment'] = items['comment']
ret['description'] = items['comment']
ret['active'] = (not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE))
ret['logonscript'] = items['script_path']
ret['profile'] = items['profile']
ret['failed_logon_attempts'] = items['bad_pw_count']
ret['successful_logon_attempts'] = items['num_logons']
secs = time.mktime(datetime.now().timetuple()) - items['password_age']
ret['password_changed'] = datetime.fromtimestamp(secs). \
strftime('%Y-%m-%d %H:%M:%S')
if items['last_logon'] == 0:
ret['last_logon'] = 'Never'
else:
ret['last_logon'] = datetime.fromtimestamp(items['last_logon']).\
strftime('%Y-%m-%d %H:%M:%S')
ret['expiration_date'] = datetime.fromtimestamp(items['acct_expires']).\
strftime('%Y-%m-%d %H:%M:%S')
ret['expired'] = items['password_expired'] == 1
if not ret['profile']:
ret['profile'] = _get_userprofile_from_registry(name, ret['uid'])
ret['home'] = items['home_dir']
ret['homedrive'] = items['home_dir_drive']
if not ret['home']:
ret['home'] = ret['profile']
ret['groups'] = groups
if items['flags'] & win32netcon.UF_DONT_EXPIRE_PASSWD == 0:
ret['password_never_expires'] = False
else:
ret['password_never_expires'] = True
if items['flags'] & win32netcon.UF_ACCOUNTDISABLE == 0:
ret['account_disabled'] = False
else:
ret['account_disabled'] = True
if items['flags'] & win32netcon.UF_LOCKOUT == 0:
ret['account_locked'] = False
else:
ret['account_locked'] = True
if items['flags'] & win32netcon.UF_PASSWD_CANT_CHANGE == 0:
ret['disallow_change_password'] = False
else:
ret['disallow_change_password'] = True
ret['gid'] = ''
return ret
else:
return {} | [
"def",
"info",
"(",
"name",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"ret",
"=",
"{",
"}",
"items",
"=",
"{",
"}",
"try",
":",
"items",
"=",
"win32net",
".",
"NetUserGetInfo",
"(",
"None",
",",
"name",... | Return user information
Args:
name (str): Username for which to display information
Returns:
dict: A dictionary containing user information
- fullname
- username
- SID
- passwd (will always return None)
- comment (same as description, left here for backwards compatibility)
- description
- active
- logonscript
- profile
- home
- homedrive
- groups
- password_changed
- successful_logon_attempts
- failed_logon_attempts
- last_logon
- account_disabled
- account_locked
- password_never_expires
- disallow_change_password
- gid
CLI Example:
.. code-block:: bash
salt '*' user.info jsnuffy | [
"Return",
"user",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L719-L825 | train |
saltstack/salt | salt/modules/win_useradd.py | _get_userprofile_from_registry | def _get_userprofile_from_registry(user, sid):
'''
In case net user doesn't return the userprofile we can get it from the
registry
Args:
user (str): The user name, used in debug message
sid (str): The sid to lookup in the registry
Returns:
str: Profile directory
'''
profile_dir = __utils__['reg.read_value'](
'HKEY_LOCAL_MACHINE',
'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{0}'.format(sid),
'ProfileImagePath'
)['vdata']
log.debug(
'user %s with sid=%s profile is located at "%s"',
user, sid, profile_dir
)
return profile_dir | python | def _get_userprofile_from_registry(user, sid):
'''
In case net user doesn't return the userprofile we can get it from the
registry
Args:
user (str): The user name, used in debug message
sid (str): The sid to lookup in the registry
Returns:
str: Profile directory
'''
profile_dir = __utils__['reg.read_value'](
'HKEY_LOCAL_MACHINE',
'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{0}'.format(sid),
'ProfileImagePath'
)['vdata']
log.debug(
'user %s with sid=%s profile is located at "%s"',
user, sid, profile_dir
)
return profile_dir | [
"def",
"_get_userprofile_from_registry",
"(",
"user",
",",
"sid",
")",
":",
"profile_dir",
"=",
"__utils__",
"[",
"'reg.read_value'",
"]",
"(",
"'HKEY_LOCAL_MACHINE'",
",",
"'SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\ProfileList\\\\{0}'",
".",
"format",
"(",
... | In case net user doesn't return the userprofile we can get it from the
registry
Args:
user (str): The user name, used in debug message
sid (str): The sid to lookup in the registry
Returns:
str: Profile directory | [
"In",
"case",
"net",
"user",
"doesn",
"t",
"return",
"the",
"userprofile",
"we",
"can",
"get",
"it",
"from",
"the",
"registry"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L828-L850 | train |
saltstack/salt | salt/modules/win_useradd.py | list_groups | def list_groups(name):
'''
Return a list of groups the named user belongs to
Args:
name (str): The user name for which to list groups
Returns:
list: A list of groups to which the user belongs
CLI Example:
.. code-block:: bash
salt '*' user.list_groups foo
'''
if six.PY2:
name = _to_unicode(name)
ugrp = set()
try:
user = info(name)['groups']
except KeyError:
return False
for group in user:
ugrp.add(group.strip(' *'))
return sorted(list(ugrp)) | python | def list_groups(name):
'''
Return a list of groups the named user belongs to
Args:
name (str): The user name for which to list groups
Returns:
list: A list of groups to which the user belongs
CLI Example:
.. code-block:: bash
salt '*' user.list_groups foo
'''
if six.PY2:
name = _to_unicode(name)
ugrp = set()
try:
user = info(name)['groups']
except KeyError:
return False
for group in user:
ugrp.add(group.strip(' *'))
return sorted(list(ugrp)) | [
"def",
"list_groups",
"(",
"name",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"ugrp",
"=",
"set",
"(",
")",
"try",
":",
"user",
"=",
"info",
"(",
"name",
")",
"[",
"'groups'",
"]",
"except",
"KeyError",
... | Return a list of groups the named user belongs to
Args:
name (str): The user name for which to list groups
Returns:
list: A list of groups to which the user belongs
CLI Example:
.. code-block:: bash
salt '*' user.list_groups foo | [
"Return",
"a",
"list",
"of",
"groups",
"the",
"named",
"user",
"belongs",
"to"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L853-L880 | train |
saltstack/salt | salt/modules/win_useradd.py | getent | def getent(refresh=False):
'''
Return the list of all info for all users
Args:
refresh (bool, optional): Refresh the cached user information. Useful
when used from within a state function. Default is False.
Returns:
dict: A dictionary containing information about all users on the system
CLI Example:
.. code-block:: bash
salt '*' user.getent
'''
if 'user.getent' in __context__ and not refresh:
return __context__['user.getent']
ret = []
for user in __salt__['user.list_users']():
stuff = {}
user_info = __salt__['user.info'](user)
stuff['gid'] = ''
stuff['groups'] = user_info['groups']
stuff['home'] = user_info['home']
stuff['name'] = user_info['name']
stuff['passwd'] = user_info['passwd']
stuff['shell'] = ''
stuff['uid'] = user_info['uid']
ret.append(stuff)
__context__['user.getent'] = ret
return ret | python | def getent(refresh=False):
'''
Return the list of all info for all users
Args:
refresh (bool, optional): Refresh the cached user information. Useful
when used from within a state function. Default is False.
Returns:
dict: A dictionary containing information about all users on the system
CLI Example:
.. code-block:: bash
salt '*' user.getent
'''
if 'user.getent' in __context__ and not refresh:
return __context__['user.getent']
ret = []
for user in __salt__['user.list_users']():
stuff = {}
user_info = __salt__['user.info'](user)
stuff['gid'] = ''
stuff['groups'] = user_info['groups']
stuff['home'] = user_info['home']
stuff['name'] = user_info['name']
stuff['passwd'] = user_info['passwd']
stuff['shell'] = ''
stuff['uid'] = user_info['uid']
ret.append(stuff)
__context__['user.getent'] = ret
return ret | [
"def",
"getent",
"(",
"refresh",
"=",
"False",
")",
":",
"if",
"'user.getent'",
"in",
"__context__",
"and",
"not",
"refresh",
":",
"return",
"__context__",
"[",
"'user.getent'",
"]",
"ret",
"=",
"[",
"]",
"for",
"user",
"in",
"__salt__",
"[",
"'user.list_u... | Return the list of all info for all users
Args:
refresh (bool, optional): Refresh the cached user information. Useful
when used from within a state function. Default is False.
Returns:
dict: A dictionary containing information about all users on the system
CLI Example:
.. code-block:: bash
salt '*' user.getent | [
"Return",
"the",
"list",
"of",
"all",
"info",
"for",
"all",
"users"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L883-L919 | train |
saltstack/salt | salt/modules/win_useradd.py | list_users | def list_users():
'''
Return a list of all users on Windows
Returns:
list: A list of all users on the system
CLI Example:
.. code-block:: bash
salt '*' user.list_users
'''
res = 0
user_list = []
dowhile = True
try:
while res or dowhile:
dowhile = False
(users, _, res) = win32net.NetUserEnum(
None,
0,
win32netcon.FILTER_NORMAL_ACCOUNT,
res,
win32netcon.MAX_PREFERRED_LENGTH
)
for user in users:
user_list.append(user['name'])
return user_list
except win32net.error:
pass | python | def list_users():
'''
Return a list of all users on Windows
Returns:
list: A list of all users on the system
CLI Example:
.. code-block:: bash
salt '*' user.list_users
'''
res = 0
user_list = []
dowhile = True
try:
while res or dowhile:
dowhile = False
(users, _, res) = win32net.NetUserEnum(
None,
0,
win32netcon.FILTER_NORMAL_ACCOUNT,
res,
win32netcon.MAX_PREFERRED_LENGTH
)
for user in users:
user_list.append(user['name'])
return user_list
except win32net.error:
pass | [
"def",
"list_users",
"(",
")",
":",
"res",
"=",
"0",
"user_list",
"=",
"[",
"]",
"dowhile",
"=",
"True",
"try",
":",
"while",
"res",
"or",
"dowhile",
":",
"dowhile",
"=",
"False",
"(",
"users",
",",
"_",
",",
"res",
")",
"=",
"win32net",
".",
"Ne... | Return a list of all users on Windows
Returns:
list: A list of all users on the system
CLI Example:
.. code-block:: bash
salt '*' user.list_users | [
"Return",
"a",
"list",
"of",
"all",
"users",
"on",
"Windows"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L922-L952 | train |
saltstack/salt | salt/modules/win_useradd.py | rename | def rename(name, new_name):
'''
Change the username for a named user
Args:
name (str): The user name to change
new_name (str): The new name for the current user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.rename jsnuffy jshmoe
'''
if six.PY2:
name = _to_unicode(name)
new_name = _to_unicode(new_name)
# Load information for the current name
current_info = info(name)
if not current_info:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
# Look for an existing user with the new name
new_info = info(new_name)
if new_info:
raise CommandExecutionError(
'User \'{0}\' already exists'.format(new_name)
)
# Rename the user account
# Connect to WMI
with salt.utils.winapi.Com():
c = wmi.WMI(find_classes=0)
# Get the user object
try:
user = c.Win32_UserAccount(Name=name)[0]
except IndexError:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
# Rename the user
result = user.Rename(new_name)[0]
# Check the result (0 means success)
if not result == 0:
# Define Error Dict
error_dict = {0: 'Success',
1: 'Instance not found',
2: 'Instance required',
3: 'Invalid parameter',
4: 'User not found',
5: 'Domain not found',
6: 'Operation is allowed only on the primary domain controller of the domain',
7: 'Operation is not allowed on the last administrative account',
8: 'Operation is not allowed on specified special groups: user, admin, local, or guest',
9: 'Other API error',
10: 'Internal error'}
raise CommandExecutionError(
'There was an error renaming \'{0}\' to \'{1}\'. Error: {2}'
.format(name, new_name, error_dict[result])
)
return info(new_name).get('name') == new_name | python | def rename(name, new_name):
'''
Change the username for a named user
Args:
name (str): The user name to change
new_name (str): The new name for the current user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.rename jsnuffy jshmoe
'''
if six.PY2:
name = _to_unicode(name)
new_name = _to_unicode(new_name)
# Load information for the current name
current_info = info(name)
if not current_info:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
# Look for an existing user with the new name
new_info = info(new_name)
if new_info:
raise CommandExecutionError(
'User \'{0}\' already exists'.format(new_name)
)
# Rename the user account
# Connect to WMI
with salt.utils.winapi.Com():
c = wmi.WMI(find_classes=0)
# Get the user object
try:
user = c.Win32_UserAccount(Name=name)[0]
except IndexError:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
# Rename the user
result = user.Rename(new_name)[0]
# Check the result (0 means success)
if not result == 0:
# Define Error Dict
error_dict = {0: 'Success',
1: 'Instance not found',
2: 'Instance required',
3: 'Invalid parameter',
4: 'User not found',
5: 'Domain not found',
6: 'Operation is allowed only on the primary domain controller of the domain',
7: 'Operation is not allowed on the last administrative account',
8: 'Operation is not allowed on specified special groups: user, admin, local, or guest',
9: 'Other API error',
10: 'Internal error'}
raise CommandExecutionError(
'There was an error renaming \'{0}\' to \'{1}\'. Error: {2}'
.format(name, new_name, error_dict[result])
)
return info(new_name).get('name') == new_name | [
"def",
"rename",
"(",
"name",
",",
"new_name",
")",
":",
"if",
"six",
".",
"PY2",
":",
"name",
"=",
"_to_unicode",
"(",
"name",
")",
"new_name",
"=",
"_to_unicode",
"(",
"new_name",
")",
"# Load information for the current name",
"current_info",
"=",
"info",
... | Change the username for a named user
Args:
name (str): The user name to change
new_name (str): The new name for the current user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.rename jsnuffy jshmoe | [
"Change",
"the",
"username",
"for",
"a",
"named",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L955-L1022 | train |
saltstack/salt | salt/modules/win_useradd.py | current | def current(sam=False):
'''
Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
Args:
sam (bool, optional): False returns just the username without any domain
notation. True returns the domain with the username in the SAM
format. Ie: ``domain\\username``
Returns:
str: Returns username
CLI Example:
.. code-block:: bash
salt '*' user.current
'''
try:
if sam:
user_name = win32api.GetUserNameEx(win32con.NameSamCompatible)
else:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
log.error('Failed to get current user')
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
raise CommandExecutionError('Failed to get current user', info=exc)
if not user_name:
raise CommandExecutionError('Failed to get current user')
return user_name | python | def current(sam=False):
'''
Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
Args:
sam (bool, optional): False returns just the username without any domain
notation. True returns the domain with the username in the SAM
format. Ie: ``domain\\username``
Returns:
str: Returns username
CLI Example:
.. code-block:: bash
salt '*' user.current
'''
try:
if sam:
user_name = win32api.GetUserNameEx(win32con.NameSamCompatible)
else:
user_name = win32api.GetUserName()
except pywintypes.error as exc:
log.error('Failed to get current user')
log.error('nbr: %s', exc.winerror)
log.error('ctx: %s', exc.funcname)
log.error('msg: %s', exc.strerror)
raise CommandExecutionError('Failed to get current user', info=exc)
if not user_name:
raise CommandExecutionError('Failed to get current user')
return user_name | [
"def",
"current",
"(",
"sam",
"=",
"False",
")",
":",
"try",
":",
"if",
"sam",
":",
"user_name",
"=",
"win32api",
".",
"GetUserNameEx",
"(",
"win32con",
".",
"NameSamCompatible",
")",
"else",
":",
"user_name",
"=",
"win32api",
".",
"GetUserName",
"(",
")... | Get the username that salt-minion is running under. If salt-minion is
running as a service it should return the Local System account. If salt is
running from a command prompt it should return the username that started the
command prompt.
.. versionadded:: 2015.5.6
Args:
sam (bool, optional): False returns just the username without any domain
notation. True returns the domain with the username in the SAM
format. Ie: ``domain\\username``
Returns:
str: Returns username
CLI Example:
.. code-block:: bash
salt '*' user.current | [
"Get",
"the",
"username",
"that",
"salt",
"-",
"minion",
"is",
"running",
"under",
".",
"If",
"salt",
"-",
"minion",
"is",
"running",
"as",
"a",
"service",
"it",
"should",
"return",
"the",
"Local",
"System",
"account",
".",
"If",
"salt",
"is",
"running",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_useradd.py#L1025-L1063 | train |
saltstack/salt | salt/utils/validate/net.py | mac | def mac(addr):
'''
Validates a mac address
'''
valid = re.compile(r'''
(^([0-9A-F]{1,2}[-]){5}([0-9A-F]{1,2})$
|^([0-9A-F]{1,2}[:]){5}([0-9A-F]{1,2})$
|^([0-9A-F]{1,2}[.]){5}([0-9A-F]{1,2})$)
''',
re.VERBOSE | re.IGNORECASE)
return valid.match(addr) is not None | python | def mac(addr):
'''
Validates a mac address
'''
valid = re.compile(r'''
(^([0-9A-F]{1,2}[-]){5}([0-9A-F]{1,2})$
|^([0-9A-F]{1,2}[:]){5}([0-9A-F]{1,2})$
|^([0-9A-F]{1,2}[.]){5}([0-9A-F]{1,2})$)
''',
re.VERBOSE | re.IGNORECASE)
return valid.match(addr) is not None | [
"def",
"mac",
"(",
"addr",
")",
":",
"valid",
"=",
"re",
".",
"compile",
"(",
"r'''\n (^([0-9A-F]{1,2}[-]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[:]){5}([0-9A-F]{1,2})$\n |^([0-9A-F]{1,2}[.]){5}([0-9A-F]{1,2})$)\n ... | Validates a mac address | [
"Validates",
"a",
"mac",
"address"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/validate/net.py#L20-L30 | train |
saltstack/salt | salt/utils/validate/net.py | __ip_addr | def __ip_addr(addr, address_family=socket.AF_INET):
'''
Returns True if the IP address (and optional subnet) are valid, otherwise
returns False.
'''
mask_max = '32'
if address_family == socket.AF_INET6:
mask_max = '128'
try:
if '/' not in addr:
addr = '{addr}/{mask_max}'.format(addr=addr, mask_max=mask_max)
except TypeError:
return False
ip, mask = addr.rsplit('/', 1)
# Verify that IP address is valid
try:
socket.inet_pton(address_family, ip)
except socket.error:
return False
# Verify that mask is valid
try:
mask = int(mask)
except ValueError:
return False
else:
if not 1 <= mask <= int(mask_max):
return False
return True | python | def __ip_addr(addr, address_family=socket.AF_INET):
'''
Returns True if the IP address (and optional subnet) are valid, otherwise
returns False.
'''
mask_max = '32'
if address_family == socket.AF_INET6:
mask_max = '128'
try:
if '/' not in addr:
addr = '{addr}/{mask_max}'.format(addr=addr, mask_max=mask_max)
except TypeError:
return False
ip, mask = addr.rsplit('/', 1)
# Verify that IP address is valid
try:
socket.inet_pton(address_family, ip)
except socket.error:
return False
# Verify that mask is valid
try:
mask = int(mask)
except ValueError:
return False
else:
if not 1 <= mask <= int(mask_max):
return False
return True | [
"def",
"__ip_addr",
"(",
"addr",
",",
"address_family",
"=",
"socket",
".",
"AF_INET",
")",
":",
"mask_max",
"=",
"'32'",
"if",
"address_family",
"==",
"socket",
".",
"AF_INET6",
":",
"mask_max",
"=",
"'128'",
"try",
":",
"if",
"'/'",
"not",
"in",
"addr"... | Returns True if the IP address (and optional subnet) are valid, otherwise
returns False. | [
"Returns",
"True",
"if",
"the",
"IP",
"address",
"(",
"and",
"optional",
"subnet",
")",
"are",
"valid",
"otherwise",
"returns",
"False",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/validate/net.py#L33-L65 | train |
saltstack/salt | salt/utils/validate/net.py | netmask | def netmask(mask):
'''
Returns True if the value passed is a valid netmask, otherwise return False
'''
if not isinstance(mask, string_types):
return False
octets = mask.split('.')
if not len(octets) == 4:
return False
return ipv4_addr(mask) and octets == sorted(octets, reverse=True) | python | def netmask(mask):
'''
Returns True if the value passed is a valid netmask, otherwise return False
'''
if not isinstance(mask, string_types):
return False
octets = mask.split('.')
if not len(octets) == 4:
return False
return ipv4_addr(mask) and octets == sorted(octets, reverse=True) | [
"def",
"netmask",
"(",
"mask",
")",
":",
"if",
"not",
"isinstance",
"(",
"mask",
",",
"string_types",
")",
":",
"return",
"False",
"octets",
"=",
"mask",
".",
"split",
"(",
"'.'",
")",
"if",
"not",
"len",
"(",
"octets",
")",
"==",
"4",
":",
"return... | Returns True if the value passed is a valid netmask, otherwise return False | [
"Returns",
"True",
"if",
"the",
"value",
"passed",
"is",
"a",
"valid",
"netmask",
"otherwise",
"return",
"False"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/validate/net.py#L92-L103 | train |
saltstack/salt | salt/modules/memcached.py | _connect | def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Returns a tuple of (user, host, port) with config, pillar, or default
values assigned to missing values.
'''
if six.text_type(port).isdigit():
return memcache.Client(['{0}:{1}'.format(host, port)], debug=0)
raise SaltInvocationError('port must be an integer') | python | def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Returns a tuple of (user, host, port) with config, pillar, or default
values assigned to missing values.
'''
if six.text_type(port).isdigit():
return memcache.Client(['{0}:{1}'.format(host, port)], debug=0)
raise SaltInvocationError('port must be an integer') | [
"def",
"_connect",
"(",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
")",
":",
"if",
"six",
".",
"text_type",
"(",
"port",
")",
".",
"isdigit",
"(",
")",
":",
"return",
"memcache",
".",
"Client",
"(",
"[",
"'{0}:{1}'",
".",
"format",
... | Returns a tuple of (user, host, port) with config, pillar, or default
values assigned to missing values. | [
"Returns",
"a",
"tuple",
"of",
"(",
"user",
"host",
"port",
")",
"with",
"config",
"pillar",
"or",
"default",
"values",
"assigned",
"to",
"missing",
"values",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L51-L58 | train |
saltstack/salt | salt/modules/memcached.py | status | def status(host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Get memcached status
CLI Example:
.. code-block:: bash
salt '*' memcached.status
'''
conn = _connect(host, port)
try:
stats = _check_stats(conn)[0]
except (CommandExecutionError, IndexError):
return False
else:
return {stats[0]: stats[1]} | python | def status(host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Get memcached status
CLI Example:
.. code-block:: bash
salt '*' memcached.status
'''
conn = _connect(host, port)
try:
stats = _check_stats(conn)[0]
except (CommandExecutionError, IndexError):
return False
else:
return {stats[0]: stats[1]} | [
"def",
"status",
"(",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
")",
":",
"conn",
"=",
"_connect",
"(",
"host",
",",
"port",
")",
"try",
":",
"stats",
"=",
"_check_stats",
"(",
"conn",
")",
"[",
"0",
"]",
"except",
"(",
"CommandE... | Get memcached status
CLI Example:
.. code-block:: bash
salt '*' memcached.status | [
"Get",
"memcached",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L74-L90 | train |
saltstack/salt | salt/modules/memcached.py | get | def get(key, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Retrieve value for a key
CLI Example:
.. code-block:: bash
salt '*' memcached.get <key>
'''
conn = _connect(host, port)
_check_stats(conn)
return conn.get(key) | python | def get(key, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Retrieve value for a key
CLI Example:
.. code-block:: bash
salt '*' memcached.get <key>
'''
conn = _connect(host, port)
_check_stats(conn)
return conn.get(key) | [
"def",
"get",
"(",
"key",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
")",
":",
"conn",
"=",
"_connect",
"(",
"host",
",",
"port",
")",
"_check_stats",
"(",
"conn",
")",
"return",
"conn",
".",
"get",
"(",
"key",
")"
] | Retrieve value for a key
CLI Example:
.. code-block:: bash
salt '*' memcached.get <key> | [
"Retrieve",
"value",
"for",
"a",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L93-L105 | train |
saltstack/salt | salt/modules/memcached.py | set_ | def set_(key,
value,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Set a key on the memcached server, overwriting the value if it exists.
CLI Example:
.. code-block:: bash
salt '*' memcached.set <key> <value>
'''
if not isinstance(time, six.integer_types):
raise SaltInvocationError('\'time\' must be an integer')
if not isinstance(min_compress_len, six.integer_types):
raise SaltInvocationError('\'min_compress_len\' must be an integer')
conn = _connect(host, port)
_check_stats(conn)
return conn.set(key, value, time, min_compress_len) | python | def set_(key,
value,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Set a key on the memcached server, overwriting the value if it exists.
CLI Example:
.. code-block:: bash
salt '*' memcached.set <key> <value>
'''
if not isinstance(time, six.integer_types):
raise SaltInvocationError('\'time\' must be an integer')
if not isinstance(min_compress_len, six.integer_types):
raise SaltInvocationError('\'min_compress_len\' must be an integer')
conn = _connect(host, port)
_check_stats(conn)
return conn.set(key, value, time, min_compress_len) | [
"def",
"set_",
"(",
"key",
",",
"value",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
",",
"time",
"=",
"DEFAULT_TIME",
",",
"min_compress_len",
"=",
"DEFAULT_MIN_COMPRESS_LEN",
")",
":",
"if",
"not",
"isinstance",
"(",
"time",
",",
... | Set a key on the memcached server, overwriting the value if it exists.
CLI Example:
.. code-block:: bash
salt '*' memcached.set <key> <value> | [
"Set",
"a",
"key",
"on",
"the",
"memcached",
"server",
"overwriting",
"the",
"value",
"if",
"it",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L108-L129 | train |
saltstack/salt | salt/modules/memcached.py | delete | def delete(key,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME):
'''
Delete a key from memcache server
CLI Example:
.. code-block:: bash
salt '*' memcached.delete <key>
'''
if not isinstance(time, six.integer_types):
raise SaltInvocationError('\'time\' must be an integer')
conn = _connect(host, port)
_check_stats(conn)
return bool(conn.delete(key, time)) | python | def delete(key,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME):
'''
Delete a key from memcache server
CLI Example:
.. code-block:: bash
salt '*' memcached.delete <key>
'''
if not isinstance(time, six.integer_types):
raise SaltInvocationError('\'time\' must be an integer')
conn = _connect(host, port)
_check_stats(conn)
return bool(conn.delete(key, time)) | [
"def",
"delete",
"(",
"key",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
",",
"time",
"=",
"DEFAULT_TIME",
")",
":",
"if",
"not",
"isinstance",
"(",
"time",
",",
"six",
".",
"integer_types",
")",
":",
"raise",
"SaltInvocationError",... | Delete a key from memcache server
CLI Example:
.. code-block:: bash
salt '*' memcached.delete <key> | [
"Delete",
"a",
"key",
"from",
"memcache",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L132-L149 | train |
saltstack/salt | salt/modules/memcached.py | replace | def replace(key,
value,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Replace a key on the memcached server. This only succeeds if the key
already exists. This is the opposite of :mod:`memcached.add
<salt.modules.memcached.add>`
CLI Example:
.. code-block:: bash
salt '*' memcached.replace <key> <value>
'''
if not isinstance(time, six.integer_types):
raise SaltInvocationError('\'time\' must be an integer')
if not isinstance(min_compress_len, six.integer_types):
raise SaltInvocationError('\'min_compress_len\' must be an integer')
conn = _connect(host, port)
stats = conn.get_stats()
return conn.replace(
key,
value,
time=time,
min_compress_len=min_compress_len
) | python | def replace(key,
value,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME,
min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
'''
Replace a key on the memcached server. This only succeeds if the key
already exists. This is the opposite of :mod:`memcached.add
<salt.modules.memcached.add>`
CLI Example:
.. code-block:: bash
salt '*' memcached.replace <key> <value>
'''
if not isinstance(time, six.integer_types):
raise SaltInvocationError('\'time\' must be an integer')
if not isinstance(min_compress_len, six.integer_types):
raise SaltInvocationError('\'min_compress_len\' must be an integer')
conn = _connect(host, port)
stats = conn.get_stats()
return conn.replace(
key,
value,
time=time,
min_compress_len=min_compress_len
) | [
"def",
"replace",
"(",
"key",
",",
"value",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
",",
"time",
"=",
"DEFAULT_TIME",
",",
"min_compress_len",
"=",
"DEFAULT_MIN_COMPRESS_LEN",
")",
":",
"if",
"not",
"isinstance",
"(",
"time",
",",... | Replace a key on the memcached server. This only succeeds if the key
already exists. This is the opposite of :mod:`memcached.add
<salt.modules.memcached.add>`
CLI Example:
.. code-block:: bash
salt '*' memcached.replace <key> <value> | [
"Replace",
"a",
"key",
"on",
"the",
"memcached",
"server",
".",
"This",
"only",
"succeeds",
"if",
"the",
"key",
"already",
"exists",
".",
"This",
"is",
"the",
"opposite",
"of",
":",
"mod",
":",
"memcached",
".",
"add",
"<salt",
".",
"modules",
".",
"me... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L182-L210 | train |
saltstack/salt | salt/modules/memcached.py | increment | def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Increment the value of a key
CLI Example:
.. code-block:: bash
salt '*' memcached.increment <key>
salt '*' memcached.increment <key> 2
'''
conn = _connect(host, port)
_check_stats(conn)
cur = get(key)
if cur is None:
raise CommandExecutionError('Key \'{0}\' does not exist'.format(key))
elif not isinstance(cur, six.integer_types):
raise CommandExecutionError(
'Value for key \'{0}\' must be an integer to be '
'incremented'.format(key)
)
try:
return conn.incr(key, delta)
except ValueError:
raise SaltInvocationError('Delta value must be an integer') | python | def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT):
'''
Increment the value of a key
CLI Example:
.. code-block:: bash
salt '*' memcached.increment <key>
salt '*' memcached.increment <key> 2
'''
conn = _connect(host, port)
_check_stats(conn)
cur = get(key)
if cur is None:
raise CommandExecutionError('Key \'{0}\' does not exist'.format(key))
elif not isinstance(cur, six.integer_types):
raise CommandExecutionError(
'Value for key \'{0}\' must be an integer to be '
'incremented'.format(key)
)
try:
return conn.incr(key, delta)
except ValueError:
raise SaltInvocationError('Delta value must be an integer') | [
"def",
"increment",
"(",
"key",
",",
"delta",
"=",
"1",
",",
"host",
"=",
"DEFAULT_HOST",
",",
"port",
"=",
"DEFAULT_PORT",
")",
":",
"conn",
"=",
"_connect",
"(",
"host",
",",
"port",
")",
"_check_stats",
"(",
"conn",
")",
"cur",
"=",
"get",
"(",
... | Increment the value of a key
CLI Example:
.. code-block:: bash
salt '*' memcached.increment <key>
salt '*' memcached.increment <key> 2 | [
"Increment",
"the",
"value",
"of",
"a",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/memcached.py#L213-L239 | train |
saltstack/salt | salt/client/ssh/wrapper/publish.py | _publish | def _publish(tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=None,
form='clean',
roster=None):
'''
Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-ssh publishes will default to whichever roster was used for the
initiating salt-ssh call, and can be overridden using the ``roster``
argument
Returners are not currently supported
The arguments sent to the minion publish function are separated with
commas. This means that for a minion executing a command with multiple
args it will look like this::
salt-ssh system.example.com publish.publish '*' user.add 'foo,1020,1020'
CLI Example:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
'''
if fun.startswith('publish.'):
log.info('Cannot publish publish calls. Returning {}')
return {}
# TODO: implement returners? Do they make sense for salt-ssh calls?
if returner:
log.warning('Returners currently not supported in salt-ssh publish')
# Make sure args have been processed
if arg is None:
arg = []
elif not isinstance(arg, list):
arg = [salt.utils.args.yamlify_arg(arg)]
else:
arg = [salt.utils.args.yamlify_arg(x) for x in arg]
if len(arg) == 1 and arg[0] is None:
arg = []
# Set up opts for the SSH object
opts = copy.deepcopy(__context__['master_opts'])
minopts = copy.deepcopy(__opts__)
opts.update(minopts)
if roster:
opts['roster'] = roster
if timeout:
opts['timeout'] = timeout
opts['argv'] = [fun] + arg
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = arg
# Create the SSH object to handle the actual call
ssh = salt.client.ssh.SSH(opts)
# Run salt-ssh to get the minion returns
rets = {}
for ret in ssh.run_iter():
rets.update(ret)
if form == 'clean':
cret = {}
for host in rets:
if 'return' in rets[host]:
cret[host] = rets[host]['return']
else:
cret[host] = rets[host]
return cret
else:
return rets | python | def _publish(tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=None,
form='clean',
roster=None):
'''
Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-ssh publishes will default to whichever roster was used for the
initiating salt-ssh call, and can be overridden using the ``roster``
argument
Returners are not currently supported
The arguments sent to the minion publish function are separated with
commas. This means that for a minion executing a command with multiple
args it will look like this::
salt-ssh system.example.com publish.publish '*' user.add 'foo,1020,1020'
CLI Example:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
'''
if fun.startswith('publish.'):
log.info('Cannot publish publish calls. Returning {}')
return {}
# TODO: implement returners? Do they make sense for salt-ssh calls?
if returner:
log.warning('Returners currently not supported in salt-ssh publish')
# Make sure args have been processed
if arg is None:
arg = []
elif not isinstance(arg, list):
arg = [salt.utils.args.yamlify_arg(arg)]
else:
arg = [salt.utils.args.yamlify_arg(x) for x in arg]
if len(arg) == 1 and arg[0] is None:
arg = []
# Set up opts for the SSH object
opts = copy.deepcopy(__context__['master_opts'])
minopts = copy.deepcopy(__opts__)
opts.update(minopts)
if roster:
opts['roster'] = roster
if timeout:
opts['timeout'] = timeout
opts['argv'] = [fun] + arg
opts['selected_target_option'] = tgt_type
opts['tgt'] = tgt
opts['arg'] = arg
# Create the SSH object to handle the actual call
ssh = salt.client.ssh.SSH(opts)
# Run salt-ssh to get the minion returns
rets = {}
for ret in ssh.run_iter():
rets.update(ret)
if form == 'clean':
cret = {}
for host in rets:
if 'return' in rets[host]:
cret[host] = rets[host]['return']
else:
cret[host] = rets[host]
return cret
else:
return rets | [
"def",
"_publish",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"returner",
"=",
"''",
",",
"timeout",
"=",
"None",
",",
"form",
"=",
"'clean'",
",",
"roster",
"=",
"None",
")",
":",
"if",
"fun",
".",
"sta... | Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-ssh publishes will default to whichever roster was used for the
initiating salt-ssh call, and can be overridden using the ``roster``
argument
Returners are not currently supported
The arguments sent to the minion publish function are separated with
commas. This means that for a minion executing a command with multiple
args it will look like this::
salt-ssh system.example.com publish.publish '*' user.add 'foo,1020,1020'
CLI Example:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' cmd.run 'ls -la /tmp' | [
"Publish",
"a",
"command",
"from",
"the",
"minion",
"out",
"to",
"other",
"minions",
".",
"In",
"reality",
"the",
"minion",
"does",
"not",
"execute",
"this",
"function",
"it",
"is",
"executed",
"by",
"the",
"master",
".",
"Thus",
"no",
"access",
"control",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/publish.py#L25-L105 | train |
saltstack/salt | salt/client/ssh/wrapper/publish.py | publish | def publish(tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=5,
roster=None):
'''
Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-ssh publishes will default to whichever roster was used for the
initiating salt-ssh call, and can be overridden using the ``roster``
argument
Returners are not currently supported
The tgt_type argument is used to pass a target other than a glob into
the execution, the available options are:
- glob
- pcre
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
The arguments sent to the minion publish function are separated with
commas. This means that for a minion executing a command with multiple
args it will look like this:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' user.add 'foo,1020,1020'
salt-ssh system.example.com publish.publish '127.0.0.1' network.interfaces '' roster=scan
CLI Example:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
.. admonition:: Attention
If you need to pass a value to a function argument and that value
contains an equal sign, you **must** include the argument name.
For example:
.. code-block:: bash
salt-ssh '*' publish.publish test.kwarg arg='cheese=spam'
Multiple keyword arguments should be passed as a list.
.. code-block:: bash
salt-ssh '*' publish.publish test.kwarg arg="['cheese=spam','spam=cheese']"
'''
return _publish(tgt,
fun,
arg=arg,
tgt_type=tgt_type,
returner=returner,
timeout=timeout,
form='clean',
roster=roster) | python | def publish(tgt,
fun,
arg=None,
tgt_type='glob',
returner='',
timeout=5,
roster=None):
'''
Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-ssh publishes will default to whichever roster was used for the
initiating salt-ssh call, and can be overridden using the ``roster``
argument
Returners are not currently supported
The tgt_type argument is used to pass a target other than a glob into
the execution, the available options are:
- glob
- pcre
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
The arguments sent to the minion publish function are separated with
commas. This means that for a minion executing a command with multiple
args it will look like this:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' user.add 'foo,1020,1020'
salt-ssh system.example.com publish.publish '127.0.0.1' network.interfaces '' roster=scan
CLI Example:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
.. admonition:: Attention
If you need to pass a value to a function argument and that value
contains an equal sign, you **must** include the argument name.
For example:
.. code-block:: bash
salt-ssh '*' publish.publish test.kwarg arg='cheese=spam'
Multiple keyword arguments should be passed as a list.
.. code-block:: bash
salt-ssh '*' publish.publish test.kwarg arg="['cheese=spam','spam=cheese']"
'''
return _publish(tgt,
fun,
arg=arg,
tgt_type=tgt_type,
returner=returner,
timeout=timeout,
form='clean',
roster=roster) | [
"def",
"publish",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"returner",
"=",
"''",
",",
"timeout",
"=",
"5",
",",
"roster",
"=",
"None",
")",
":",
"return",
"_publish",
"(",
"tgt",
",",
"fun",
",",
"arg... | Publish a command "from the minion out to other minions". In reality, the
minion does not execute this function, it is executed by the master. Thus,
no access control is enabled, as minions cannot initiate publishes
themselves.
Salt-ssh publishes will default to whichever roster was used for the
initiating salt-ssh call, and can be overridden using the ``roster``
argument
Returners are not currently supported
The tgt_type argument is used to pass a target other than a glob into
the execution, the available options are:
- glob
- pcre
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
The arguments sent to the minion publish function are separated with
commas. This means that for a minion executing a command with multiple
args it will look like this:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' user.add 'foo,1020,1020'
salt-ssh system.example.com publish.publish '127.0.0.1' network.interfaces '' roster=scan
CLI Example:
.. code-block:: bash
salt-ssh system.example.com publish.publish '*' cmd.run 'ls -la /tmp'
.. admonition:: Attention
If you need to pass a value to a function argument and that value
contains an equal sign, you **must** include the argument name.
For example:
.. code-block:: bash
salt-ssh '*' publish.publish test.kwarg arg='cheese=spam'
Multiple keyword arguments should be passed as a list.
.. code-block:: bash
salt-ssh '*' publish.publish test.kwarg arg="['cheese=spam','spam=cheese']" | [
"Publish",
"a",
"command",
"from",
"the",
"minion",
"out",
"to",
"other",
"minions",
".",
"In",
"reality",
"the",
"minion",
"does",
"not",
"execute",
"this",
"function",
"it",
"is",
"executed",
"by",
"the",
"master",
".",
"Thus",
"no",
"access",
"control",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/publish.py#L108-L180 | train |
saltstack/salt | salt/client/ssh/wrapper/publish.py | runner | def runner(fun, arg=None, timeout=5):
'''
Execute a runner on the master and return the data from the runnr function
CLI Example:
.. code-block:: bash
salt-ssh '*' publish.runner jobs.lookup_jid 20140916125524463507
'''
# Form args as list
if not isinstance(arg, list):
arg = [salt.utils.args.yamlify_arg(arg)]
else:
arg = [salt.utils.args.yamlify_arg(x) for x in arg]
if len(arg) == 1 and arg[0] is None:
arg = []
# Create and run the runner
runner = salt.runner.RunnerClient(__opts__['__master_opts__'])
return runner.cmd(fun, arg) | python | def runner(fun, arg=None, timeout=5):
'''
Execute a runner on the master and return the data from the runnr function
CLI Example:
.. code-block:: bash
salt-ssh '*' publish.runner jobs.lookup_jid 20140916125524463507
'''
# Form args as list
if not isinstance(arg, list):
arg = [salt.utils.args.yamlify_arg(arg)]
else:
arg = [salt.utils.args.yamlify_arg(x) for x in arg]
if len(arg) == 1 and arg[0] is None:
arg = []
# Create and run the runner
runner = salt.runner.RunnerClient(__opts__['__master_opts__'])
return runner.cmd(fun, arg) | [
"def",
"runner",
"(",
"fun",
",",
"arg",
"=",
"None",
",",
"timeout",
"=",
"5",
")",
":",
"# Form args as list",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"list",
")",
":",
"arg",
"=",
"[",
"salt",
".",
"utils",
".",
"args",
".",
"yamlify_arg",
"... | Execute a runner on the master and return the data from the runnr function
CLI Example:
.. code-block:: bash
salt-ssh '*' publish.runner jobs.lookup_jid 20140916125524463507 | [
"Execute",
"a",
"runner",
"on",
"the",
"master",
"and",
"return",
"the",
"data",
"from",
"the",
"runnr",
"function"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/client/ssh/wrapper/publish.py#L221-L241 | train |
saltstack/salt | salt/utils/openstack/pyrax/queues.py | RackspaceQueues.create | def create(self, qname):
'''
Create RackSpace Queue.
'''
try:
if self.exists(qname):
log.error('Queues "%s" already exists. Nothing done.', qname)
return True
self.conn.create(qname)
return True
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during creation: %s',
err_msg)
return False | python | def create(self, qname):
'''
Create RackSpace Queue.
'''
try:
if self.exists(qname):
log.error('Queues "%s" already exists. Nothing done.', qname)
return True
self.conn.create(qname)
return True
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during creation: %s',
err_msg)
return False | [
"def",
"create",
"(",
"self",
",",
"qname",
")",
":",
"try",
":",
"if",
"self",
".",
"exists",
"(",
"qname",
")",
":",
"log",
".",
"error",
"(",
"'Queues \"%s\" already exists. Nothing done.'",
",",
"qname",
")",
"return",
"True",
"self",
".",
"conn",
".... | Create RackSpace Queue. | [
"Create",
"RackSpace",
"Queue",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/pyrax/queues.py#L25-L40 | train |
saltstack/salt | salt/utils/openstack/pyrax/queues.py | RackspaceQueues.delete | def delete(self, qname):
'''
Delete an existings RackSpace Queue.
'''
try:
q = self.exists(qname)
if not q:
return False
queue = self.show(qname)
if queue:
queue.delete()
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during deletion: %s',
err_msg)
return False
return True | python | def delete(self, qname):
'''
Delete an existings RackSpace Queue.
'''
try:
q = self.exists(qname)
if not q:
return False
queue = self.show(qname)
if queue:
queue.delete()
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during deletion: %s',
err_msg)
return False
return True | [
"def",
"delete",
"(",
"self",
",",
"qname",
")",
":",
"try",
":",
"q",
"=",
"self",
".",
"exists",
"(",
"qname",
")",
"if",
"not",
"q",
":",
"return",
"False",
"queue",
"=",
"self",
".",
"show",
"(",
"qname",
")",
"if",
"queue",
":",
"queue",
"... | Delete an existings RackSpace Queue. | [
"Delete",
"an",
"existings",
"RackSpace",
"Queue",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/pyrax/queues.py#L42-L58 | train |
saltstack/salt | salt/utils/openstack/pyrax/queues.py | RackspaceQueues.exists | def exists(self, qname):
'''
Check to see if a Queue exists.
'''
try:
# First if not exists() -> exit
if self.conn.queue_exists(qname):
return True
return False
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during '
'existing queue check: %s',
err_msg)
return False | python | def exists(self, qname):
'''
Check to see if a Queue exists.
'''
try:
# First if not exists() -> exit
if self.conn.queue_exists(qname):
return True
return False
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during '
'existing queue check: %s',
err_msg)
return False | [
"def",
"exists",
"(",
"self",
",",
"qname",
")",
":",
"try",
":",
"# First if not exists() -> exit",
"if",
"self",
".",
"conn",
".",
"queue_exists",
"(",
"qname",
")",
":",
"return",
"True",
"return",
"False",
"except",
"pyrax",
".",
"exceptions",
"as",
"e... | Check to see if a Queue exists. | [
"Check",
"to",
"see",
"if",
"a",
"Queue",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/pyrax/queues.py#L60-L73 | train |
saltstack/salt | salt/utils/openstack/pyrax/queues.py | RackspaceQueues.show | def show(self, qname):
'''
Show information about Queue
'''
try:
# First if not exists() -> exit
if not self.conn.queue_exists(qname):
return {}
# If exist, search the queue to return the Queue Object
for queue in self.conn.list():
if queue.name == qname:
return queue
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during existing'
' queue check: %s', err_msg)
return {} | python | def show(self, qname):
'''
Show information about Queue
'''
try:
# First if not exists() -> exit
if not self.conn.queue_exists(qname):
return {}
# If exist, search the queue to return the Queue Object
for queue in self.conn.list():
if queue.name == qname:
return queue
except pyrax.exceptions as err_msg:
log.error('RackSpace API got some problems during existing'
' queue check: %s', err_msg)
return {} | [
"def",
"show",
"(",
"self",
",",
"qname",
")",
":",
"try",
":",
"# First if not exists() -> exit",
"if",
"not",
"self",
".",
"conn",
".",
"queue_exists",
"(",
"qname",
")",
":",
"return",
"{",
"}",
"# If exist, search the queue to return the Queue Object",
"for",
... | Show information about Queue | [
"Show",
"information",
"about",
"Queue"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/openstack/pyrax/queues.py#L75-L90 | train |
saltstack/salt | salt/modules/win_autoruns.py | _get_dirs | def _get_dirs(user_dir, startup_dir):
'''
Return a list of startup dirs
'''
try:
users = os.listdir(user_dir)
except WindowsError: # pylint: disable=E0602
users = []
full_dirs = []
for user in users:
full_dir = os.path.join(user_dir, user, startup_dir)
if os.path.exists(full_dir):
full_dirs.append(full_dir)
return full_dirs | python | def _get_dirs(user_dir, startup_dir):
'''
Return a list of startup dirs
'''
try:
users = os.listdir(user_dir)
except WindowsError: # pylint: disable=E0602
users = []
full_dirs = []
for user in users:
full_dir = os.path.join(user_dir, user, startup_dir)
if os.path.exists(full_dir):
full_dirs.append(full_dir)
return full_dirs | [
"def",
"_get_dirs",
"(",
"user_dir",
",",
"startup_dir",
")",
":",
"try",
":",
"users",
"=",
"os",
".",
"listdir",
"(",
"user_dir",
")",
"except",
"WindowsError",
":",
"# pylint: disable=E0602",
"users",
"=",
"[",
"]",
"full_dirs",
"=",
"[",
"]",
"for",
... | Return a list of startup dirs | [
"Return",
"a",
"list",
"of",
"startup",
"dirs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_autoruns.py#L34-L48 | train |
saltstack/salt | salt/modules/win_autoruns.py | list_ | def list_():
'''
Get a list of automatically running programs
CLI Example:
.. code-block:: bash
salt '*' autoruns.list
'''
autoruns = {}
# Find autoruns in registry
keys = ['HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run',
'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /reg:64',
'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
]
for key in keys:
autoruns[key] = []
cmd = ['reg', 'query', key]
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if line and line[0:4] != "HKEY" and line[0:5] != "ERROR": # Remove junk lines
autoruns[key].append(line)
# Find autoruns in user's startup folder
user_dir = 'C:\\Documents and Settings\\'
startup_dir = '\\Start Menu\\Programs\\Startup'
full_dirs = _get_dirs(user_dir, startup_dir)
if not full_dirs:
user_dir = 'C:\\Users\\'
startup_dir = '\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'
full_dirs = _get_dirs(user_dir, startup_dir)
for full_dir in full_dirs:
files = os.listdir(full_dir)
autoruns[full_dir] = []
for single_file in files:
autoruns[full_dir].append(single_file)
return autoruns | python | def list_():
'''
Get a list of automatically running programs
CLI Example:
.. code-block:: bash
salt '*' autoruns.list
'''
autoruns = {}
# Find autoruns in registry
keys = ['HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run',
'HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run /reg:64',
'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
]
for key in keys:
autoruns[key] = []
cmd = ['reg', 'query', key]
for line in __salt__['cmd.run'](cmd, python_shell=False).splitlines():
if line and line[0:4] != "HKEY" and line[0:5] != "ERROR": # Remove junk lines
autoruns[key].append(line)
# Find autoruns in user's startup folder
user_dir = 'C:\\Documents and Settings\\'
startup_dir = '\\Start Menu\\Programs\\Startup'
full_dirs = _get_dirs(user_dir, startup_dir)
if not full_dirs:
user_dir = 'C:\\Users\\'
startup_dir = '\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup'
full_dirs = _get_dirs(user_dir, startup_dir)
for full_dir in full_dirs:
files = os.listdir(full_dir)
autoruns[full_dir] = []
for single_file in files:
autoruns[full_dir].append(single_file)
return autoruns | [
"def",
"list_",
"(",
")",
":",
"autoruns",
"=",
"{",
"}",
"# Find autoruns in registry",
"keys",
"=",
"[",
"'HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run'",
",",
"'HKLM\\\\Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run /reg:64'",
",",
"'HKCU\\\\Softw... | Get a list of automatically running programs
CLI Example:
.. code-block:: bash
salt '*' autoruns.list | [
"Get",
"a",
"list",
"of",
"automatically",
"running",
"programs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_autoruns.py#L51-L90 | train |
saltstack/salt | salt/pillar/vault.py | ext_pillar | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf,
nesting_key=None):
'''
Get pillar data from Vault for the configuration ``conf``.
'''
comps = conf.split()
paths = [comp for comp in comps if comp.startswith('path=')]
if not paths:
log.error('"%s" is not a valid Vault ext_pillar config', conf)
return {}
vault_pillar = {}
try:
path = paths[0].replace('path=', '')
path = path.format(**{'minion': minion_id})
url = 'v1/{0}'.format(path)
response = __utils__['vault.make_request']('GET', url)
if response.status_code == 200:
vault_pillar = response.json().get('data', {})
else:
log.info('Vault secret not found for: %s', path)
except KeyError:
log.error('No such path in Vault: %s', path)
if nesting_key:
vault_pillar = {nesting_key: vault_pillar}
return vault_pillar | python | def ext_pillar(minion_id, # pylint: disable=W0613
pillar, # pylint: disable=W0613
conf,
nesting_key=None):
'''
Get pillar data from Vault for the configuration ``conf``.
'''
comps = conf.split()
paths = [comp for comp in comps if comp.startswith('path=')]
if not paths:
log.error('"%s" is not a valid Vault ext_pillar config', conf)
return {}
vault_pillar = {}
try:
path = paths[0].replace('path=', '')
path = path.format(**{'minion': minion_id})
url = 'v1/{0}'.format(path)
response = __utils__['vault.make_request']('GET', url)
if response.status_code == 200:
vault_pillar = response.json().get('data', {})
else:
log.info('Vault secret not found for: %s', path)
except KeyError:
log.error('No such path in Vault: %s', path)
if nesting_key:
vault_pillar = {nesting_key: vault_pillar}
return vault_pillar | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"# pylint: disable=W0613",
"pillar",
",",
"# pylint: disable=W0613",
"conf",
",",
"nesting_key",
"=",
"None",
")",
":",
"comps",
"=",
"conf",
".",
"split",
"(",
")",
"paths",
"=",
"[",
"comp",
"for",
"comp",
"in",
... | Get pillar data from Vault for the configuration ``conf``. | [
"Get",
"pillar",
"data",
"from",
"Vault",
"for",
"the",
"configuration",
"conf",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/vault.py#L142-L172 | train |
saltstack/salt | salt/states/svn.py | export | def export(name,
target=None,
rev=None,
user=None,
username=None,
password=None,
force=False,
overwrite=False,
externals=True,
trust=False,
trust_failures=None):
'''
Export a file or directory from an SVN repository
name
Address and path to the file or directory to be exported.
target
Name of the target directory where the checkout will put the working
directory
rev : None
The name revision number to checkout. Enable "force" if the directory
already exists.
user : None
Name of the user performing repository management operations
username : None
The user to access the name repository with. The svn default is the
current user
password
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
force : False
Continue if conflicts are encountered
overwrite : False
Overwrite existing target
externals : True
Change to False to not checkout or update externals
trust : False
Automatically trust the remote server. SVN's --trust-server-cert
trust_failures : None
Comma-separated list of certificate trust failures, that shall be
ignored. This can be used if trust=True is not sufficient. The
specified string is passed to SVN's --trust-server-cert-failures
option as-is.
.. versionadded:: 2019.2.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not target:
return _fail(ret, 'Target option is required')
svn_cmd = 'svn.export'
cwd, basename = os.path.split(target)
opts = tuple()
if not overwrite and os.path.exists(target) and not os.path.isdir(target):
return _fail(ret,
'The path "{0}" exists and is not '
'a directory.'.format(target)
)
if __opts__['test']:
if not os.path.exists(target):
return _neutral_test(
ret,
('{0} doesn\'t exist and is set to be checked out.').format(target))
svn_cmd = 'svn.list'
rev = 'HEAD'
out = __salt__[svn_cmd](cwd, target, user, username, password, *opts)
return _neutral_test(
ret,
('{0}').format(out))
if not rev:
rev = 'HEAD'
if force:
opts += ('--force',)
if externals is False:
opts += ('--ignore-externals',)
if trust:
opts += ('--trust-server-cert',)
if trust_failures:
opts += ('--trust-server-cert-failures', trust_failures)
out = __salt__[svn_cmd](cwd, name, basename, user, username, password, rev, *opts)
ret['changes']['new'] = name
ret['changes']['comment'] = name + ' was Exported to ' + target
return ret | python | def export(name,
target=None,
rev=None,
user=None,
username=None,
password=None,
force=False,
overwrite=False,
externals=True,
trust=False,
trust_failures=None):
'''
Export a file or directory from an SVN repository
name
Address and path to the file or directory to be exported.
target
Name of the target directory where the checkout will put the working
directory
rev : None
The name revision number to checkout. Enable "force" if the directory
already exists.
user : None
Name of the user performing repository management operations
username : None
The user to access the name repository with. The svn default is the
current user
password
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
force : False
Continue if conflicts are encountered
overwrite : False
Overwrite existing target
externals : True
Change to False to not checkout or update externals
trust : False
Automatically trust the remote server. SVN's --trust-server-cert
trust_failures : None
Comma-separated list of certificate trust failures, that shall be
ignored. This can be used if trust=True is not sufficient. The
specified string is passed to SVN's --trust-server-cert-failures
option as-is.
.. versionadded:: 2019.2.0
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if not target:
return _fail(ret, 'Target option is required')
svn_cmd = 'svn.export'
cwd, basename = os.path.split(target)
opts = tuple()
if not overwrite and os.path.exists(target) and not os.path.isdir(target):
return _fail(ret,
'The path "{0}" exists and is not '
'a directory.'.format(target)
)
if __opts__['test']:
if not os.path.exists(target):
return _neutral_test(
ret,
('{0} doesn\'t exist and is set to be checked out.').format(target))
svn_cmd = 'svn.list'
rev = 'HEAD'
out = __salt__[svn_cmd](cwd, target, user, username, password, *opts)
return _neutral_test(
ret,
('{0}').format(out))
if not rev:
rev = 'HEAD'
if force:
opts += ('--force',)
if externals is False:
opts += ('--ignore-externals',)
if trust:
opts += ('--trust-server-cert',)
if trust_failures:
opts += ('--trust-server-cert-failures', trust_failures)
out = __salt__[svn_cmd](cwd, name, basename, user, username, password, rev, *opts)
ret['changes']['new'] = name
ret['changes']['comment'] = name + ' was Exported to ' + target
return ret | [
"def",
"export",
"(",
"name",
",",
"target",
"=",
"None",
",",
"rev",
"=",
"None",
",",
"user",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"force",
"=",
"False",
",",
"overwrite",
"=",
"False",
",",
"externals",
"... | Export a file or directory from an SVN repository
name
Address and path to the file or directory to be exported.
target
Name of the target directory where the checkout will put the working
directory
rev : None
The name revision number to checkout. Enable "force" if the directory
already exists.
user : None
Name of the user performing repository management operations
username : None
The user to access the name repository with. The svn default is the
current user
password
Connect to the Subversion server with this password
.. versionadded:: 0.17.0
force : False
Continue if conflicts are encountered
overwrite : False
Overwrite existing target
externals : True
Change to False to not checkout or update externals
trust : False
Automatically trust the remote server. SVN's --trust-server-cert
trust_failures : None
Comma-separated list of certificate trust failures, that shall be
ignored. This can be used if trust=True is not sufficient. The
specified string is passed to SVN's --trust-server-cert-failures
option as-is.
.. versionadded:: 2019.2.0 | [
"Export",
"a",
"file",
"or",
"directory",
"from",
"an",
"SVN",
"repository"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/svn.py#L190-L291 | train |
saltstack/salt | salt/states/svn.py | dirty | def dirty(name,
target,
user=None,
username=None,
password=None,
ignore_unversioned=False):
'''
Determine if the working directory has been changed.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
return _fail(ret, 'This function is not implemented yet.') | python | def dirty(name,
target,
user=None,
username=None,
password=None,
ignore_unversioned=False):
'''
Determine if the working directory has been changed.
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
return _fail(ret, 'This function is not implemented yet.') | [
"def",
"dirty",
"(",
"name",
",",
"target",
",",
"user",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"ignore_unversioned",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",... | Determine if the working directory has been changed. | [
"Determine",
"if",
"the",
"working",
"directory",
"has",
"been",
"changed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/svn.py#L294-L304 | train |
saltstack/salt | salt/pillar/saltclass.py | ext_pillar | def ext_pillar(minion_id, pillar, *args, **kwargs):
'''
Compile pillar data
'''
# Node definitions path will be retrieved from args (or set to default),
# then added to 'salt_data' dict that is passed to the 'get_pillars'
# function. The dictionary contains:
# - __opts__
# - __salt__
# - __grains__
# - __pillar__
# - minion_id
# - path
#
# If successful, the function will return a pillar dict for minion_id.
# If path has not been set, make a default
for i in args:
if 'path' not in i:
path = '/srv/saltclass'
args[i]['path'] = path
log.warning('path variable unset, using default: %s', path)
else:
path = i['path']
# Create a dict that will contain our salt dicts to pass it to reclass
salt_data = {
'__opts__': __opts__,
'__salt__': __salt__,
'__grains__': __grains__,
'__pillar__': pillar,
'minion_id': minion_id,
'path': path
}
return sc.get_pillars(minion_id, salt_data) | python | def ext_pillar(minion_id, pillar, *args, **kwargs):
'''
Compile pillar data
'''
# Node definitions path will be retrieved from args (or set to default),
# then added to 'salt_data' dict that is passed to the 'get_pillars'
# function. The dictionary contains:
# - __opts__
# - __salt__
# - __grains__
# - __pillar__
# - minion_id
# - path
#
# If successful, the function will return a pillar dict for minion_id.
# If path has not been set, make a default
for i in args:
if 'path' not in i:
path = '/srv/saltclass'
args[i]['path'] = path
log.warning('path variable unset, using default: %s', path)
else:
path = i['path']
# Create a dict that will contain our salt dicts to pass it to reclass
salt_data = {
'__opts__': __opts__,
'__salt__': __salt__,
'__grains__': __grains__,
'__pillar__': pillar,
'minion_id': minion_id,
'path': path
}
return sc.get_pillars(minion_id, salt_data) | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Node definitions path will be retrieved from args (or set to default),",
"# then added to 'salt_data' dict that is passed to the 'get_pillars'",
"# function. The dictionary... | Compile pillar data | [
"Compile",
"pillar",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/saltclass.py#L30-L65 | train |
saltstack/salt | salt/states/libcloud_storage.py | container_present | def container_present(name, profile):
'''
Ensures a container is present.
:param name: Container name
:type name: ``str``
:param profile: The profile key
:type profile: ``str``
'''
containers = __salt__['libcloud_storage.list_containers'](profile)
match = [z for z in containers if z['name'] == name]
if match:
return state_result(True, "Container already exists", name, {})
else:
result = __salt__['libcloud_storage.create_container'](name, profile)
return state_result(True, "Created new container", name, result) | python | def container_present(name, profile):
'''
Ensures a container is present.
:param name: Container name
:type name: ``str``
:param profile: The profile key
:type profile: ``str``
'''
containers = __salt__['libcloud_storage.list_containers'](profile)
match = [z for z in containers if z['name'] == name]
if match:
return state_result(True, "Container already exists", name, {})
else:
result = __salt__['libcloud_storage.create_container'](name, profile)
return state_result(True, "Created new container", name, result) | [
"def",
"container_present",
"(",
"name",
",",
"profile",
")",
":",
"containers",
"=",
"__salt__",
"[",
"'libcloud_storage.list_containers'",
"]",
"(",
"profile",
")",
"match",
"=",
"[",
"z",
"for",
"z",
"in",
"containers",
"if",
"z",
"[",
"'name'",
"]",
"=... | Ensures a container is present.
:param name: Container name
:type name: ``str``
:param profile: The profile key
:type profile: ``str`` | [
"Ensures",
"a",
"container",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_storage.py#L92-L108 | train |
saltstack/salt | salt/states/libcloud_storage.py | object_present | def object_present(container, name, path, profile):
'''
Ensures a object is presnt.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_object = __salt__['libcloud_storage.get_container_object'](container, name, profile)
if existing_object is not None:
return state_result(True, "Object already present", name, {})
else:
result = __salt__['libcloud_storage.upload_object'](path, container, name, profile)
return state_result(result, "Uploaded object", name, {}) | python | def object_present(container, name, path, profile):
'''
Ensures a object is presnt.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_object = __salt__['libcloud_storage.get_container_object'](container, name, profile)
if existing_object is not None:
return state_result(True, "Object already present", name, {})
else:
result = __salt__['libcloud_storage.upload_object'](path, container, name, profile)
return state_result(result, "Uploaded object", name, {}) | [
"def",
"object_present",
"(",
"container",
",",
"name",
",",
"path",
",",
"profile",
")",
":",
"existing_object",
"=",
"__salt__",
"[",
"'libcloud_storage.get_container_object'",
"]",
"(",
"container",
",",
"name",
",",
"profile",
")",
"if",
"existing_object",
"... | Ensures a object is presnt.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile key
:type profile: ``str`` | [
"Ensures",
"a",
"object",
"is",
"presnt",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_storage.py#L130-L151 | train |
saltstack/salt | salt/states/libcloud_storage.py | object_absent | def object_absent(container, name, profile):
'''
Ensures a object is absent.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_object = __salt__['libcloud_storage.get_container_object'](container, name, profile)
if existing_object is None:
return state_result(True, "Object already absent", name, {})
else:
result = __salt__['libcloud_storage.delete_object'](container, name, profile)
return state_result(result, "Deleted object", name, {}) | python | def object_absent(container, name, profile):
'''
Ensures a object is absent.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param profile: The profile key
:type profile: ``str``
'''
existing_object = __salt__['libcloud_storage.get_container_object'](container, name, profile)
if existing_object is None:
return state_result(True, "Object already absent", name, {})
else:
result = __salt__['libcloud_storage.delete_object'](container, name, profile)
return state_result(result, "Deleted object", name, {}) | [
"def",
"object_absent",
"(",
"container",
",",
"name",
",",
"profile",
")",
":",
"existing_object",
"=",
"__salt__",
"[",
"'libcloud_storage.get_container_object'",
"]",
"(",
"container",
",",
"name",
",",
"profile",
")",
"if",
"existing_object",
"is",
"None",
"... | Ensures a object is absent.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param profile: The profile key
:type profile: ``str`` | [
"Ensures",
"a",
"object",
"is",
"absent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_storage.py#L154-L172 | train |
saltstack/salt | salt/states/libcloud_storage.py | file_present | def file_present(container, name, path, profile, overwrite_existing=False):
'''
Ensures a object is downloaded locally.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile key
:type profile: ``str``
:param overwrite_existing: Replace if already exists
:type overwrite_existing: ``bool``
'''
result = __salt__['libcloud_storage.download_object'](path, container, name, profile, overwrite_existing)
return state_result(result, "Downloaded object", name, {}) | python | def file_present(container, name, path, profile, overwrite_existing=False):
'''
Ensures a object is downloaded locally.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile key
:type profile: ``str``
:param overwrite_existing: Replace if already exists
:type overwrite_existing: ``bool``
'''
result = __salt__['libcloud_storage.download_object'](path, container, name, profile, overwrite_existing)
return state_result(result, "Downloaded object", name, {}) | [
"def",
"file_present",
"(",
"container",
",",
"name",
",",
"path",
",",
"profile",
",",
"overwrite_existing",
"=",
"False",
")",
":",
"result",
"=",
"__salt__",
"[",
"'libcloud_storage.download_object'",
"]",
"(",
"path",
",",
"container",
",",
"name",
",",
... | Ensures a object is downloaded locally.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile key
:type profile: ``str``
:param overwrite_existing: Replace if already exists
:type overwrite_existing: ``bool`` | [
"Ensures",
"a",
"object",
"is",
"downloaded",
"locally",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/libcloud_storage.py#L175-L195 | train |
saltstack/salt | salt/proxy/nxos.py | init | def init(opts=None):
'''
Required.
Initialize device connection using ssh or nxapi connection type.
'''
global CONNECTION
if __opts__.get('proxy').get('connection') is not None:
CONNECTION = __opts__.get('proxy').get('connection')
if CONNECTION == 'ssh':
log.info('NXOS PROXY: Initialize ssh proxy connection')
return _init_ssh(opts)
elif CONNECTION == 'nxapi':
log.info('NXOS PROXY: Initialize nxapi proxy connection')
return _init_nxapi(opts)
else:
log.error('Unknown Connection Type: %s', CONNECTION)
return False | python | def init(opts=None):
'''
Required.
Initialize device connection using ssh or nxapi connection type.
'''
global CONNECTION
if __opts__.get('proxy').get('connection') is not None:
CONNECTION = __opts__.get('proxy').get('connection')
if CONNECTION == 'ssh':
log.info('NXOS PROXY: Initialize ssh proxy connection')
return _init_ssh(opts)
elif CONNECTION == 'nxapi':
log.info('NXOS PROXY: Initialize nxapi proxy connection')
return _init_nxapi(opts)
else:
log.error('Unknown Connection Type: %s', CONNECTION)
return False | [
"def",
"init",
"(",
"opts",
"=",
"None",
")",
":",
"global",
"CONNECTION",
"if",
"__opts__",
".",
"get",
"(",
"'proxy'",
")",
".",
"get",
"(",
"'connection'",
")",
"is",
"not",
"None",
":",
"CONNECTION",
"=",
"__opts__",
".",
"get",
"(",
"'proxy'",
"... | Required.
Initialize device connection using ssh or nxapi connection type. | [
"Required",
".",
"Initialize",
"device",
"connection",
"using",
"ssh",
"or",
"nxapi",
"connection",
"type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L210-L227 | train |
saltstack/salt | salt/proxy/nxos.py | grains | def grains(**kwargs):
'''
Get grains for minion.
.. code-block: bash
salt '*' nxos.cmd grains
'''
import __main__ as main # pylint: disable=unused-import
if not DEVICE_DETAILS['grains_cache']:
data = sendline('show version')
if CONNECTION == 'nxapi':
data = data[0]
ret = salt.utils.nxos.system_info(data)
log.debug(ret)
DEVICE_DETAILS['grains_cache'].update(ret['nxos'])
return {'nxos': DEVICE_DETAILS['grains_cache']} | python | def grains(**kwargs):
'''
Get grains for minion.
.. code-block: bash
salt '*' nxos.cmd grains
'''
import __main__ as main # pylint: disable=unused-import
if not DEVICE_DETAILS['grains_cache']:
data = sendline('show version')
if CONNECTION == 'nxapi':
data = data[0]
ret = salt.utils.nxos.system_info(data)
log.debug(ret)
DEVICE_DETAILS['grains_cache'].update(ret['nxos'])
return {'nxos': DEVICE_DETAILS['grains_cache']} | [
"def",
"grains",
"(",
"*",
"*",
"kwargs",
")",
":",
"import",
"__main__",
"as",
"main",
"# pylint: disable=unused-import",
"if",
"not",
"DEVICE_DETAILS",
"[",
"'grains_cache'",
"]",
":",
"data",
"=",
"sendline",
"(",
"'show version'",
")",
"if",
"CONNECTION",
... | Get grains for minion.
.. code-block: bash
salt '*' nxos.cmd grains | [
"Get",
"grains",
"for",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L256-L272 | train |
saltstack/salt | salt/proxy/nxos.py | sendline | def sendline(command, method='cli_show_ascii', **kwargs):
'''
Send arbitrary show or config commands to the NX-OS device.
command
The command to be sent.
method:
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_show_ascii``.
NOTES for SSH proxy minon:
``method`` is ignored for SSH proxy minion.
Only show commands are supported and data is returned unstructured.
This function is preserved for backwards compatibilty.
.. code-block: bash
salt '*' nxos.cmd sendline 'show run | include "^username admin password"'
'''
try:
if CONNECTION == 'ssh':
result = _sendline_ssh(command, **kwargs)
elif CONNECTION == 'nxapi':
result = _nxapi_request(command, method, **kwargs)
except (TerminalException, NxosCliError) as e:
log.error(e)
raise
return result | python | def sendline(command, method='cli_show_ascii', **kwargs):
'''
Send arbitrary show or config commands to the NX-OS device.
command
The command to be sent.
method:
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_show_ascii``.
NOTES for SSH proxy minon:
``method`` is ignored for SSH proxy minion.
Only show commands are supported and data is returned unstructured.
This function is preserved for backwards compatibilty.
.. code-block: bash
salt '*' nxos.cmd sendline 'show run | include "^username admin password"'
'''
try:
if CONNECTION == 'ssh':
result = _sendline_ssh(command, **kwargs)
elif CONNECTION == 'nxapi':
result = _nxapi_request(command, method, **kwargs)
except (TerminalException, NxosCliError) as e:
log.error(e)
raise
return result | [
"def",
"sendline",
"(",
"command",
",",
"method",
"=",
"'cli_show_ascii'",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"if",
"CONNECTION",
"==",
"'ssh'",
":",
"result",
"=",
"_sendline_ssh",
"(",
"command",
",",
"*",
"*",
"kwargs",
")",
"elif",
"CON... | Send arbitrary show or config commands to the NX-OS device.
command
The command to be sent.
method:
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_show_ascii``.
NOTES for SSH proxy minon:
``method`` is ignored for SSH proxy minion.
Only show commands are supported and data is returned unstructured.
This function is preserved for backwards compatibilty.
.. code-block: bash
salt '*' nxos.cmd sendline 'show run | include "^username admin password"' | [
"Send",
"arbitrary",
"show",
"or",
"config",
"commands",
"to",
"the",
"NX",
"-",
"OS",
"device",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L297-L327 | train |
saltstack/salt | salt/proxy/nxos.py | proxy_config | def proxy_config(commands, **kwargs):
'''
Send configuration commands over SSH or NX-API
commands
List of configuration commands
no_save_config
If True, don't save configuration commands to startup configuration.
If False, save configuration to startup configuration.
Default: False
.. code-block: bash
salt '*' nxos.cmd proxy_config 'feature bgp' no_save_config=True
salt '*' nxos.cmd proxy_config 'feature bgp'
'''
no_save_config = DEVICE_DETAILS['no_save_config']
no_save_config = kwargs.get('no_save_config', no_save_config)
if not isinstance(commands, list):
commands = [commands]
try:
if CONNECTION == 'ssh':
_sendline_ssh('config terminal')
single_cmd = ''
for cmd in commands:
single_cmd += cmd + ' ; '
ret = _sendline_ssh(single_cmd + 'end')
if no_save_config:
pass
else:
_sendline_ssh(COPY_RS)
if ret:
log.error(ret)
elif CONNECTION == 'nxapi':
ret = _nxapi_request(commands)
if no_save_config:
pass
else:
_nxapi_request(COPY_RS)
for each in ret:
if 'Failure' in each:
log.error(each)
except CommandExecutionError as e:
log.error(e)
raise
return [commands, ret] | python | def proxy_config(commands, **kwargs):
'''
Send configuration commands over SSH or NX-API
commands
List of configuration commands
no_save_config
If True, don't save configuration commands to startup configuration.
If False, save configuration to startup configuration.
Default: False
.. code-block: bash
salt '*' nxos.cmd proxy_config 'feature bgp' no_save_config=True
salt '*' nxos.cmd proxy_config 'feature bgp'
'''
no_save_config = DEVICE_DETAILS['no_save_config']
no_save_config = kwargs.get('no_save_config', no_save_config)
if not isinstance(commands, list):
commands = [commands]
try:
if CONNECTION == 'ssh':
_sendline_ssh('config terminal')
single_cmd = ''
for cmd in commands:
single_cmd += cmd + ' ; '
ret = _sendline_ssh(single_cmd + 'end')
if no_save_config:
pass
else:
_sendline_ssh(COPY_RS)
if ret:
log.error(ret)
elif CONNECTION == 'nxapi':
ret = _nxapi_request(commands)
if no_save_config:
pass
else:
_nxapi_request(COPY_RS)
for each in ret:
if 'Failure' in each:
log.error(each)
except CommandExecutionError as e:
log.error(e)
raise
return [commands, ret] | [
"def",
"proxy_config",
"(",
"commands",
",",
"*",
"*",
"kwargs",
")",
":",
"no_save_config",
"=",
"DEVICE_DETAILS",
"[",
"'no_save_config'",
"]",
"no_save_config",
"=",
"kwargs",
".",
"get",
"(",
"'no_save_config'",
",",
"no_save_config",
")",
"if",
"not",
"is... | Send configuration commands over SSH or NX-API
commands
List of configuration commands
no_save_config
If True, don't save configuration commands to startup configuration.
If False, save configuration to startup configuration.
Default: False
.. code-block: bash
salt '*' nxos.cmd proxy_config 'feature bgp' no_save_config=True
salt '*' nxos.cmd proxy_config 'feature bgp' | [
"Send",
"configuration",
"commands",
"over",
"SSH",
"or",
"NX",
"-",
"API"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L330-L376 | train |
saltstack/salt | salt/proxy/nxos.py | _init_ssh | def _init_ssh(opts):
'''
Open a connection to the NX-OS switch over SSH.
'''
if opts is None:
opts = __opts__
try:
this_prompt = None
if 'prompt_regex' in opts['proxy']:
this_prompt = opts['proxy']['prompt_regex']
elif 'prompt_name' in opts['proxy']:
this_prompt = '{0}.*#'.format(opts['proxy']['prompt_name'])
else:
log.warning('nxos proxy configuration does not specify a prompt match.')
this_prompt = '.+#$'
DEVICE_DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt=this_prompt)
out, err = DEVICE_DETAILS[_worker_name()].sendline('terminal length 0')
log.info('SSH session establised for process %s', _worker_name())
except Exception as ex:
log.error('Unable to connect to %s', opts['proxy']['host'])
log.error('Please check the following:\n')
log.error('-- Verify that "feature ssh" is enabled on your NX-OS device: %s', opts['proxy']['host'])
log.error('-- Exception Generated: %s', ex)
log.error(ex)
exit()
DEVICE_DETAILS['initialized'] = True
DEVICE_DETAILS['no_save_config'] = opts['proxy'].get('no_save_config', False) | python | def _init_ssh(opts):
'''
Open a connection to the NX-OS switch over SSH.
'''
if opts is None:
opts = __opts__
try:
this_prompt = None
if 'prompt_regex' in opts['proxy']:
this_prompt = opts['proxy']['prompt_regex']
elif 'prompt_name' in opts['proxy']:
this_prompt = '{0}.*#'.format(opts['proxy']['prompt_name'])
else:
log.warning('nxos proxy configuration does not specify a prompt match.')
this_prompt = '.+#$'
DEVICE_DETAILS[_worker_name()] = SSHConnection(
host=opts['proxy']['host'],
username=opts['proxy']['username'],
password=opts['proxy']['password'],
key_accept=opts['proxy'].get('key_accept', False),
ssh_args=opts['proxy'].get('ssh_args', ''),
prompt=this_prompt)
out, err = DEVICE_DETAILS[_worker_name()].sendline('terminal length 0')
log.info('SSH session establised for process %s', _worker_name())
except Exception as ex:
log.error('Unable to connect to %s', opts['proxy']['host'])
log.error('Please check the following:\n')
log.error('-- Verify that "feature ssh" is enabled on your NX-OS device: %s', opts['proxy']['host'])
log.error('-- Exception Generated: %s', ex)
log.error(ex)
exit()
DEVICE_DETAILS['initialized'] = True
DEVICE_DETAILS['no_save_config'] = opts['proxy'].get('no_save_config', False) | [
"def",
"_init_ssh",
"(",
"opts",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"__opts__",
"try",
":",
"this_prompt",
"=",
"None",
"if",
"'prompt_regex'",
"in",
"opts",
"[",
"'proxy'",
"]",
":",
"this_prompt",
"=",
"opts",
"[",
"'proxy'",
"]"... | Open a connection to the NX-OS switch over SSH. | [
"Open",
"a",
"connection",
"to",
"the",
"NX",
"-",
"OS",
"switch",
"over",
"SSH",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L382-L415 | train |
saltstack/salt | salt/proxy/nxos.py | _parse_output_for_errors | def _parse_output_for_errors(data, command, **kwargs):
'''
Helper method to parse command output for error information
'''
if re.search('% Invalid', data):
raise CommandExecutionError({
'rejected_input': command,
'message': 'CLI excution error',
'code': '400',
'cli_error': data.lstrip(),
})
if kwargs.get('error_pattern') is not None:
for re_line in kwargs.get('error_pattern'):
if re.search(re_line, data):
raise CommandExecutionError({
'rejected_input': command,
'message': 'CLI excution error',
'code': '400',
'cli_error': data.lstrip(),
}) | python | def _parse_output_for_errors(data, command, **kwargs):
'''
Helper method to parse command output for error information
'''
if re.search('% Invalid', data):
raise CommandExecutionError({
'rejected_input': command,
'message': 'CLI excution error',
'code': '400',
'cli_error': data.lstrip(),
})
if kwargs.get('error_pattern') is not None:
for re_line in kwargs.get('error_pattern'):
if re.search(re_line, data):
raise CommandExecutionError({
'rejected_input': command,
'message': 'CLI excution error',
'code': '400',
'cli_error': data.lstrip(),
}) | [
"def",
"_parse_output_for_errors",
"(",
"data",
",",
"command",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"re",
".",
"search",
"(",
"'% Invalid'",
",",
"data",
")",
":",
"raise",
"CommandExecutionError",
"(",
"{",
"'rejected_input'",
":",
"command",
",",
"'... | Helper method to parse command output for error information | [
"Helper",
"method",
"to",
"parse",
"command",
"output",
"for",
"error",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L446-L465 | train |
saltstack/salt | salt/proxy/nxos.py | _init_nxapi | def _init_nxapi(opts):
'''
Open a connection to the NX-OS switch over NX-API.
As the communication is HTTP(S) based, there is no connection to maintain,
however, in order to test the connectivity and make sure we are able to
bring up this Minion, we are executing a very simple command (``show clock``)
which doesn't come with much overhead and it's sufficient to confirm we are
indeed able to connect to the NX-API endpoint as configured.
'''
proxy_dict = opts.get('proxy', {})
conn_args = copy.deepcopy(proxy_dict)
conn_args.pop('proxytype', None)
opts['multiprocessing'] = conn_args.pop('multiprocessing', True)
# This is not a SSH-based proxy, so it should be safe to enable
# multiprocessing.
try:
rpc_reply = __utils__['nxos.nxapi_request']('show clock', **conn_args)
# Execute a very simple command to confirm we are able to connect properly
DEVICE_DETAILS['conn_args'] = conn_args
DEVICE_DETAILS['initialized'] = True
DEVICE_DETAILS['up'] = True
DEVICE_DETAILS['no_save_config'] = opts['proxy'].get('no_save_config', False)
except Exception as ex:
log.error('Unable to connect to %s', conn_args['host'])
log.error('Please check the following:\n')
log.error('-- Verify that "feature nxapi" is enabled on your NX-OS device: %s', conn_args['host'])
log.error('-- Verify that nxapi settings on the NX-OS device and proxy minion config file match')
log.error('-- Exception Generated: %s', ex)
exit()
log.info('nxapi DEVICE_DETAILS info: %s', DEVICE_DETAILS)
return True | python | def _init_nxapi(opts):
'''
Open a connection to the NX-OS switch over NX-API.
As the communication is HTTP(S) based, there is no connection to maintain,
however, in order to test the connectivity and make sure we are able to
bring up this Minion, we are executing a very simple command (``show clock``)
which doesn't come with much overhead and it's sufficient to confirm we are
indeed able to connect to the NX-API endpoint as configured.
'''
proxy_dict = opts.get('proxy', {})
conn_args = copy.deepcopy(proxy_dict)
conn_args.pop('proxytype', None)
opts['multiprocessing'] = conn_args.pop('multiprocessing', True)
# This is not a SSH-based proxy, so it should be safe to enable
# multiprocessing.
try:
rpc_reply = __utils__['nxos.nxapi_request']('show clock', **conn_args)
# Execute a very simple command to confirm we are able to connect properly
DEVICE_DETAILS['conn_args'] = conn_args
DEVICE_DETAILS['initialized'] = True
DEVICE_DETAILS['up'] = True
DEVICE_DETAILS['no_save_config'] = opts['proxy'].get('no_save_config', False)
except Exception as ex:
log.error('Unable to connect to %s', conn_args['host'])
log.error('Please check the following:\n')
log.error('-- Verify that "feature nxapi" is enabled on your NX-OS device: %s', conn_args['host'])
log.error('-- Verify that nxapi settings on the NX-OS device and proxy minion config file match')
log.error('-- Exception Generated: %s', ex)
exit()
log.info('nxapi DEVICE_DETAILS info: %s', DEVICE_DETAILS)
return True | [
"def",
"_init_nxapi",
"(",
"opts",
")",
":",
"proxy_dict",
"=",
"opts",
".",
"get",
"(",
"'proxy'",
",",
"{",
"}",
")",
"conn_args",
"=",
"copy",
".",
"deepcopy",
"(",
"proxy_dict",
")",
"conn_args",
".",
"pop",
"(",
"'proxytype'",
",",
"None",
")",
... | Open a connection to the NX-OS switch over NX-API.
As the communication is HTTP(S) based, there is no connection to maintain,
however, in order to test the connectivity and make sure we are able to
bring up this Minion, we are executing a very simple command (``show clock``)
which doesn't come with much overhead and it's sufficient to confirm we are
indeed able to connect to the NX-API endpoint as configured. | [
"Open",
"a",
"connection",
"to",
"the",
"NX",
"-",
"OS",
"switch",
"over",
"NX",
"-",
"API",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L475-L506 | train |
saltstack/salt | salt/proxy/nxos.py | _nxapi_request | def _nxapi_request(commands, method='cli_conf', **kwargs):
'''
Executes an nxapi_request request over NX-API.
commands
The exec or config commands to be sent.
method: ``cli_show``
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_conf``.
'''
if CONNECTION == 'ssh':
return '_nxapi_request is not available for ssh proxy'
conn_args = DEVICE_DETAILS['conn_args']
conn_args.update(kwargs)
data = __utils__['nxos.nxapi_request'](commands, method=method, **conn_args)
return data | python | def _nxapi_request(commands, method='cli_conf', **kwargs):
'''
Executes an nxapi_request request over NX-API.
commands
The exec or config commands to be sent.
method: ``cli_show``
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_conf``.
'''
if CONNECTION == 'ssh':
return '_nxapi_request is not available for ssh proxy'
conn_args = DEVICE_DETAILS['conn_args']
conn_args.update(kwargs)
data = __utils__['nxos.nxapi_request'](commands, method=method, **conn_args)
return data | [
"def",
"_nxapi_request",
"(",
"commands",
",",
"method",
"=",
"'cli_conf'",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"CONNECTION",
"==",
"'ssh'",
":",
"return",
"'_nxapi_request is not available for ssh proxy'",
"conn_args",
"=",
"DEVICE_DETAILS",
"[",
"'conn_args'"... | Executes an nxapi_request request over NX-API.
commands
The exec or config commands to be sent.
method: ``cli_show``
``cli_show_ascii``: Return raw test or unstructured output.
``cli_show``: Return structured output.
``cli_conf``: Send configuration commands to the device.
Defaults to ``cli_conf``. | [
"Executes",
"an",
"nxapi_request",
"request",
"over",
"NX",
"-",
"API",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/nxos.py#L521-L539 | train |
saltstack/salt | salt/modules/azurearm_compute.py | availability_set_create_or_update | def availability_set_create_or_update(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Create or update an availability set.
:param name: The availability set to create.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_create_or_update testset testgroup
'''
if 'location' not in kwargs:
rg_props = __salt__['azurearm_resource.resource_group_get'](
resource_group, **kwargs
)
if 'error' in rg_props:
log.error(
'Unable to determine location from resource group specified.'
)
return False
kwargs['location'] = rg_props['location']
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
# Use VM names to link to the IDs of existing VMs.
if isinstance(kwargs.get('virtual_machines'), list):
vm_list = []
for vm_name in kwargs.get('virtual_machines'):
vm_instance = __salt__['azurearm_compute.virtual_machine_get'](
name=vm_name,
resource_group=resource_group,
**kwargs
)
if 'error' not in vm_instance:
vm_list.append({'id': str(vm_instance['id'])})
kwargs['virtual_machines'] = vm_list
try:
setmodel = __utils__['azurearm.create_object_model']('compute', 'AvailabilitySet', **kwargs)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
av_set = compconn.availability_sets.create_or_update(
resource_group_name=resource_group,
availability_set_name=name,
parameters=setmodel
)
result = av_set.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | python | def availability_set_create_or_update(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Create or update an availability set.
:param name: The availability set to create.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_create_or_update testset testgroup
'''
if 'location' not in kwargs:
rg_props = __salt__['azurearm_resource.resource_group_get'](
resource_group, **kwargs
)
if 'error' in rg_props:
log.error(
'Unable to determine location from resource group specified.'
)
return False
kwargs['location'] = rg_props['location']
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
# Use VM names to link to the IDs of existing VMs.
if isinstance(kwargs.get('virtual_machines'), list):
vm_list = []
for vm_name in kwargs.get('virtual_machines'):
vm_instance = __salt__['azurearm_compute.virtual_machine_get'](
name=vm_name,
resource_group=resource_group,
**kwargs
)
if 'error' not in vm_instance:
vm_list.append({'id': str(vm_instance['id'])})
kwargs['virtual_machines'] = vm_list
try:
setmodel = __utils__['azurearm.create_object_model']('compute', 'AvailabilitySet', **kwargs)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
av_set = compconn.availability_sets.create_or_update(
resource_group_name=resource_group,
availability_set_name=name,
parameters=setmodel
)
result = av_set.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | [
"def",
"availability_set_create_or_update",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"if",
"'location'",
"not",
"in",
"kwargs",
":",
"rg_props",
"=",
"__salt__",
"[",
"'azurearm_resource.resource_group_get'... | .. versionadded:: 2019.2.0
Create or update an availability set.
:param name: The availability set to create.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_create_or_update testset testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L80-L145 | train |
saltstack/salt | salt/modules/azurearm_compute.py | availability_set_delete | def availability_set_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete an availability set.
:param name: The availability set to delete.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_delete testset testgroup
'''
result = False
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
compconn.availability_sets.delete(
resource_group_name=resource_group,
availability_set_name=name
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
return result | python | def availability_set_delete(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete an availability set.
:param name: The availability set to delete.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_delete testset testgroup
'''
result = False
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
compconn.availability_sets.delete(
resource_group_name=resource_group,
availability_set_name=name
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
return result | [
"def",
"availability_set_delete",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"c... | .. versionadded:: 2019.2.0
Delete an availability set.
:param name: The availability set to delete.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_delete testset testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L148-L178 | train |
saltstack/salt | salt/modules/azurearm_compute.py | availability_set_get | def availability_set_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a dictionary representing an availability set's properties.
:param name: The availability set to get.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_get testset testgroup
'''
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
av_set = compconn.availability_sets.get(
resource_group_name=resource_group,
availability_set_name=name
)
result = av_set.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def availability_set_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a dictionary representing an availability set's properties.
:param name: The availability set to get.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_get testset testgroup
'''
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
av_set = compconn.availability_sets.get(
resource_group_name=resource_group,
availability_set_name=name
)
result = av_set.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"availability_set_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"av_set",
"=",
"compconn",
".... | .. versionadded:: 2019.2.0
Get a dictionary representing an availability set's properties.
:param name: The availability set to get.
:param resource_group: The resource group name assigned to the
availability set.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_set_get testset testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L181-L211 | train |
saltstack/salt | salt/modules/azurearm_compute.py | availability_sets_list | def availability_sets_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all availability sets within a resource group.
:param resource_group: The resource group name to list availability
sets within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_sets_list testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
avail_sets = __utils__['azurearm.paged_object_to_list'](
compconn.availability_sets.list(
resource_group_name=resource_group
)
)
for avail_set in avail_sets:
result[avail_set['name']] = avail_set
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def availability_sets_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all availability sets within a resource group.
:param resource_group: The resource group name to list availability
sets within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_sets_list testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
avail_sets = __utils__['azurearm.paged_object_to_list'](
compconn.availability_sets.list(
resource_group_name=resource_group
)
)
for avail_set in avail_sets:
result[avail_set['name']] = avail_set
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"availability_sets_list",
"(",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"avail_sets",
"... | .. versionadded:: 2019.2.0
List all availability sets within a resource group.
:param resource_group: The resource group name to list availability
sets within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_sets_list testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L214-L245 | train |
saltstack/salt | salt/modules/azurearm_compute.py | availability_sets_list_available_sizes | def availability_sets_list_available_sizes(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
List all available virtual machine sizes that can be used to
to create a new virtual machine in an existing availability set.
:param name: The availability set name to list available
virtual machine sizes within.
:param resource_group: The resource group name to list available
availability set sizes within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_sets_list_available_sizes testset testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
sizes = __utils__['azurearm.paged_object_to_list'](
compconn.availability_sets.list_available_sizes(
resource_group_name=resource_group,
availability_set_name=name
)
)
for size in sizes:
result[size['name']] = size
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def availability_sets_list_available_sizes(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
List all available virtual machine sizes that can be used to
to create a new virtual machine in an existing availability set.
:param name: The availability set name to list available
virtual machine sizes within.
:param resource_group: The resource group name to list available
availability set sizes within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_sets_list_available_sizes testset testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
sizes = __utils__['azurearm.paged_object_to_list'](
compconn.availability_sets.list_available_sizes(
resource_group_name=resource_group,
availability_set_name=name
)
)
for size in sizes:
result[size['name']] = size
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"availability_sets_list_available_sizes",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"result",
"=",
"{",
"}",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",... | .. versionadded:: 2019.2.0
List all available virtual machine sizes that can be used to
to create a new virtual machine in an existing availability set.
:param name: The availability set name to list available
virtual machine sizes within.
:param resource_group: The resource group name to list available
availability set sizes within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.availability_sets_list_available_sizes testset testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L248-L284 | train |
saltstack/salt | salt/modules/azurearm_compute.py | virtual_machine_capture | def virtual_machine_capture(name, destination_name, resource_group, prefix='capture-', overwrite=False, **kwargs):
'''
.. versionadded:: 2019.2.0
Captures the VM by copying virtual hard disks of the VM and outputs
a template that can be used to create similar VMs.
:param name: The name of the virtual machine.
:param destination_name: The destination container name.
:param resource_group: The resource group name assigned to the
virtual machine.
:param prefix: (Default: 'capture-') The captured virtual hard disk's name prefix.
:param overwrite: (Default: False) Overwrite the destination disk in case of conflict.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_capture testvm testcontainer testgroup
'''
# pylint: disable=invalid-name
VirtualMachineCaptureParameters = getattr(
azure.mgmt.compute.models, 'VirtualMachineCaptureParameters'
)
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
# pylint: disable=invalid-name
vm = compconn.virtual_machines.capture(
resource_group_name=resource_group,
vm_name=name,
parameters=VirtualMachineCaptureParameters(
vhd_prefix=prefix,
destination_container_name=destination_name,
overwrite_vhds=overwrite
)
)
vm.wait()
vm_result = vm.result()
result = vm_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def virtual_machine_capture(name, destination_name, resource_group, prefix='capture-', overwrite=False, **kwargs):
'''
.. versionadded:: 2019.2.0
Captures the VM by copying virtual hard disks of the VM and outputs
a template that can be used to create similar VMs.
:param name: The name of the virtual machine.
:param destination_name: The destination container name.
:param resource_group: The resource group name assigned to the
virtual machine.
:param prefix: (Default: 'capture-') The captured virtual hard disk's name prefix.
:param overwrite: (Default: False) Overwrite the destination disk in case of conflict.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_capture testvm testcontainer testgroup
'''
# pylint: disable=invalid-name
VirtualMachineCaptureParameters = getattr(
azure.mgmt.compute.models, 'VirtualMachineCaptureParameters'
)
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
# pylint: disable=invalid-name
vm = compconn.virtual_machines.capture(
resource_group_name=resource_group,
vm_name=name,
parameters=VirtualMachineCaptureParameters(
vhd_prefix=prefix,
destination_container_name=destination_name,
overwrite_vhds=overwrite
)
)
vm.wait()
vm_result = vm.result()
result = vm_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"virtual_machine_capture",
"(",
"name",
",",
"destination_name",
",",
"resource_group",
",",
"prefix",
"=",
"'capture-'",
",",
"overwrite",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"VirtualMachineCaptureParameters",
"="... | .. versionadded:: 2019.2.0
Captures the VM by copying virtual hard disks of the VM and outputs
a template that can be used to create similar VMs.
:param name: The name of the virtual machine.
:param destination_name: The destination container name.
:param resource_group: The resource group name assigned to the
virtual machine.
:param prefix: (Default: 'capture-') The captured virtual hard disk's name prefix.
:param overwrite: (Default: False) Overwrite the destination disk in case of conflict.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_capture testvm testcontainer testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L287-L336 | train |
saltstack/salt | salt/modules/azurearm_compute.py | virtual_machine_get | def virtual_machine_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Retrieves information about the model view or the instance view of a
virtual machine.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_get testvm testgroup
'''
expand = kwargs.get('expand')
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
# pylint: disable=invalid-name
vm = compconn.virtual_machines.get(
resource_group_name=resource_group,
vm_name=name,
expand=expand
)
result = vm.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def virtual_machine_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Retrieves information about the model view or the instance view of a
virtual machine.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_get testvm testgroup
'''
expand = kwargs.get('expand')
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
# pylint: disable=invalid-name
vm = compconn.virtual_machines.get(
resource_group_name=resource_group,
vm_name=name,
expand=expand
)
result = vm.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"virtual_machine_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"expand",
"=",
"kwargs",
".",
"get",
"(",
"'expand'",
")",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*"... | .. versionadded:: 2019.2.0
Retrieves information about the model view or the instance view of a
virtual machine.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_get testvm testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L339-L373 | train |
saltstack/salt | salt/modules/azurearm_compute.py | virtual_machine_convert_to_managed_disks | def virtual_machine_convert_to_managed_disks(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Converts virtual machine disks from blob-based to managed disks. Virtual
machine must be stop-deallocated before invoking this operation.
:param name: The name of the virtual machine to convert.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_convert_to_managed_disks testvm testgroup
'''
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
# pylint: disable=invalid-name
vm = compconn.virtual_machines.convert_to_managed_disks(
resource_group_name=resource_group,
vm_name=name
)
vm.wait()
vm_result = vm.result()
result = vm_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def virtual_machine_convert_to_managed_disks(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Converts virtual machine disks from blob-based to managed disks. Virtual
machine must be stop-deallocated before invoking this operation.
:param name: The name of the virtual machine to convert.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_convert_to_managed_disks testvm testgroup
'''
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
# pylint: disable=invalid-name
vm = compconn.virtual_machines.convert_to_managed_disks(
resource_group_name=resource_group,
vm_name=name
)
vm.wait()
vm_result = vm.result()
result = vm_result.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"virtual_machine_convert_to_managed_disks",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")... | .. versionadded:: 2019.2.0
Converts virtual machine disks from blob-based to managed disks. Virtual
machine must be stop-deallocated before invoking this operation.
:param name: The name of the virtual machine to convert.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_convert_to_managed_disks testvm testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L376-L409 | train |
saltstack/salt | salt/modules/azurearm_compute.py | virtual_machine_generalize | def virtual_machine_generalize(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Set the state of a virtual machine to 'generalized'.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_generalize testvm testgroup
'''
result = False
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
compconn.virtual_machines.generalize(
resource_group_name=resource_group,
vm_name=name
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
return result | python | def virtual_machine_generalize(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Set the state of a virtual machine to 'generalized'.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_generalize testvm testgroup
'''
result = False
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
compconn.virtual_machines.generalize(
resource_group_name=resource_group,
vm_name=name
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
return result | [
"def",
"virtual_machine_generalize",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
... | .. versionadded:: 2019.2.0
Set the state of a virtual machine to 'generalized'.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machine_generalize testvm testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L447-L476 | train |
saltstack/salt | salt/modules/azurearm_compute.py | virtual_machines_list | def virtual_machines_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual machines within a resource group.
:param resource_group: The resource group name to list virtual
machines within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
vms = __utils__['azurearm.paged_object_to_list'](
compconn.virtual_machines.list(
resource_group_name=resource_group
)
)
for vm in vms: # pylint: disable=invalid-name
result[vm['name']] = vm
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def virtual_machines_list(resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual machines within a resource group.
:param resource_group: The resource group name to list virtual
machines within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
vms = __utils__['azurearm.paged_object_to_list'](
compconn.virtual_machines.list(
resource_group_name=resource_group
)
)
for vm in vms: # pylint: disable=invalid-name
result[vm['name']] = vm
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"virtual_machines_list",
"(",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"vms",
"=",
"_... | .. versionadded:: 2019.2.0
List all virtual machines within a resource group.
:param resource_group: The resource group name to list virtual
machines within.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L479-L509 | train |
saltstack/salt | salt/modules/azurearm_compute.py | virtual_machines_list_all | def virtual_machines_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
vms = __utils__['azurearm.paged_object_to_list'](
compconn.virtual_machines.list_all()
)
for vm in vms: # pylint: disable=invalid-name
result[vm['name']] = vm
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def virtual_machines_list_all(**kwargs):
'''
.. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
vms = __utils__['azurearm.paged_object_to_list'](
compconn.virtual_machines.list_all()
)
for vm in vms: # pylint: disable=invalid-name
result[vm['name']] = vm
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"virtual_machines_list_all",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"vms",
"=",
"__utils__",
"[",
"'a... | .. versionadded:: 2019.2.0
List all virtual machines within a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_all | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L512-L537 | train |
saltstack/salt | salt/modules/azurearm_compute.py | virtual_machines_list_available_sizes | def virtual_machines_list_available_sizes(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Lists all available virtual machine sizes to which the specified virtual
machine can be resized.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_available_sizes testvm testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
sizes = __utils__['azurearm.paged_object_to_list'](
compconn.virtual_machines.list_available_sizes(
resource_group_name=resource_group,
vm_name=name
)
)
for size in sizes:
result[size['name']] = size
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def virtual_machines_list_available_sizes(name, resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Lists all available virtual machine sizes to which the specified virtual
machine can be resized.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_available_sizes testvm testgroup
'''
result = {}
compconn = __utils__['azurearm.get_client']('compute', **kwargs)
try:
sizes = __utils__['azurearm.paged_object_to_list'](
compconn.virtual_machines.list_available_sizes(
resource_group_name=resource_group,
vm_name=name
)
)
for size in sizes:
result[size['name']] = size
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('compute', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"virtual_machines_list_available_sizes",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"result",
"=",
"{",
"}",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
... | .. versionadded:: 2019.2.0
Lists all available virtual machine sizes to which the specified virtual
machine can be resized.
:param name: The name of the virtual machine.
:param resource_group: The resource group name assigned to the
virtual machine.
CLI Example:
.. code-block:: bash
salt-call azurearm_compute.virtual_machines_list_available_sizes testvm testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_compute.py#L540-L574 | train |
saltstack/salt | salt/output/yaml_out.py | output | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print out YAML using the block mode
'''
params = {}
if 'output_indent' not in __opts__:
# default indentation
params.update(default_flow_style=False)
elif __opts__['output_indent'] >= 0:
# custom indent
params.update(default_flow_style=False,
indent=__opts__['output_indent'])
else: # no indentation
params.update(default_flow_style=True,
indent=0)
try:
return salt.utils.yaml.safe_dump(data, **params)
except Exception as exc:
import pprint
log.exception(
'Exception %s encountered when trying to serialize %s',
exc, pprint.pformat(data)
) | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print out YAML using the block mode
'''
params = {}
if 'output_indent' not in __opts__:
# default indentation
params.update(default_flow_style=False)
elif __opts__['output_indent'] >= 0:
# custom indent
params.update(default_flow_style=False,
indent=__opts__['output_indent'])
else: # no indentation
params.update(default_flow_style=True,
indent=0)
try:
return salt.utils.yaml.safe_dump(data, **params)
except Exception as exc:
import pprint
log.exception(
'Exception %s encountered when trying to serialize %s',
exc, pprint.pformat(data)
) | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"params",
"=",
"{",
"}",
"if",
"'output_indent'",
"not",
"in",
"__opts__",
":",
"# default indentation",
"params",
".",
"update",
"(",
"default_flow_style",
"="... | Print out YAML using the block mode | [
"Print",
"out",
"YAML",
"using",
"the",
"block",
"mode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/yaml_out.py#L38-L61 | train |
saltstack/salt | salt/utils/yast.py | mksls | def mksls(src, dst=None):
'''
Convert an AutoYAST file to an SLS file
'''
with salt.utils.files.fopen(src, 'r') as fh_:
ps_opts = xml.to_dict(ET.fromstring(fh_.read()))
if dst is not None:
with salt.utils.files.fopen(dst, 'w') as fh_:
salt.utils.yaml.safe_dump(ps_opts, fh_, default_flow_style=False)
else:
return salt.utils.yaml.safe_dump(ps_opts, default_flow_style=False) | python | def mksls(src, dst=None):
'''
Convert an AutoYAST file to an SLS file
'''
with salt.utils.files.fopen(src, 'r') as fh_:
ps_opts = xml.to_dict(ET.fromstring(fh_.read()))
if dst is not None:
with salt.utils.files.fopen(dst, 'w') as fh_:
salt.utils.yaml.safe_dump(ps_opts, fh_, default_flow_style=False)
else:
return salt.utils.yaml.safe_dump(ps_opts, default_flow_style=False) | [
"def",
"mksls",
"(",
"src",
",",
"dst",
"=",
"None",
")",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"src",
",",
"'r'",
")",
"as",
"fh_",
":",
"ps_opts",
"=",
"xml",
".",
"to_dict",
"(",
"ET",
".",
"fromstring",
"(",
"f... | Convert an AutoYAST file to an SLS file | [
"Convert",
"an",
"AutoYAST",
"file",
"to",
"an",
"SLS",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/yast.py#L14-L25 | train |
saltstack/salt | salt/utils/color.py | get_color_theme | def get_color_theme(theme):
'''
Return the color theme to use
'''
# Keep the heavy lifting out of the module space
import salt.utils.data
import salt.utils.files
import salt.utils.yaml
if not os.path.isfile(theme):
log.warning('The named theme %s if not available', theme)
try:
with salt.utils.files.fopen(theme, 'rb') as fp_:
colors = salt.utils.data.decode(salt.utils.yaml.safe_load(fp_))
ret = {}
for color in colors:
ret[color] = '\033[{0}m'.format(colors[color])
if not isinstance(colors, dict):
log.warning('The theme file %s is not a dict', theme)
return {}
return ret
except Exception:
log.warning('Failed to read the color theme %s', theme)
return {} | python | def get_color_theme(theme):
'''
Return the color theme to use
'''
# Keep the heavy lifting out of the module space
import salt.utils.data
import salt.utils.files
import salt.utils.yaml
if not os.path.isfile(theme):
log.warning('The named theme %s if not available', theme)
try:
with salt.utils.files.fopen(theme, 'rb') as fp_:
colors = salt.utils.data.decode(salt.utils.yaml.safe_load(fp_))
ret = {}
for color in colors:
ret[color] = '\033[{0}m'.format(colors[color])
if not isinstance(colors, dict):
log.warning('The theme file %s is not a dict', theme)
return {}
return ret
except Exception:
log.warning('Failed to read the color theme %s', theme)
return {} | [
"def",
"get_color_theme",
"(",
"theme",
")",
":",
"# Keep the heavy lifting out of the module space",
"import",
"salt",
".",
"utils",
".",
"data",
"import",
"salt",
".",
"utils",
".",
"files",
"import",
"salt",
".",
"utils",
".",
"yaml",
"if",
"not",
"os",
"."... | Return the color theme to use | [
"Return",
"the",
"color",
"theme",
"to",
"use"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/color.py#L18-L41 | train |
saltstack/salt | salt/utils/color.py | get_colors | def get_colors(use=True, theme=None):
'''
Return the colors as an easy to use dict. Pass `False` to deactivate all
colors by setting them to empty strings. Pass a string containing only the
name of a single color to be used in place of all colors. Examples:
.. code-block:: python
colors = get_colors() # enable all colors
no_colors = get_colors(False) # disable all colors
red_colors = get_colors('RED') # set all colors to red
'''
colors = {
'BLACK': TextFormat('black'),
'DARK_GRAY': TextFormat('bold', 'black'),
'RED': TextFormat('red'),
'LIGHT_RED': TextFormat('bold', 'red'),
'GREEN': TextFormat('green'),
'LIGHT_GREEN': TextFormat('bold', 'green'),
'YELLOW': TextFormat('yellow'),
'LIGHT_YELLOW': TextFormat('bold', 'yellow'),
'BLUE': TextFormat('blue'),
'LIGHT_BLUE': TextFormat('bold', 'blue'),
'MAGENTA': TextFormat('magenta'),
'LIGHT_MAGENTA': TextFormat('bold', 'magenta'),
'CYAN': TextFormat('cyan'),
'LIGHT_CYAN': TextFormat('bold', 'cyan'),
'LIGHT_GRAY': TextFormat('white'),
'WHITE': TextFormat('bold', 'white'),
'DEFAULT_COLOR': TextFormat('default'),
'ENDC': TextFormat('reset'),
}
if theme:
colors.update(get_color_theme(theme))
if not use:
for color in colors:
colors[color] = ''
if isinstance(use, six.string_types):
# Try to set all of the colors to the passed color
if use in colors:
for color in colors:
# except for color reset
if color == 'ENDC':
continue
colors[color] = colors[use]
return colors | python | def get_colors(use=True, theme=None):
'''
Return the colors as an easy to use dict. Pass `False` to deactivate all
colors by setting them to empty strings. Pass a string containing only the
name of a single color to be used in place of all colors. Examples:
.. code-block:: python
colors = get_colors() # enable all colors
no_colors = get_colors(False) # disable all colors
red_colors = get_colors('RED') # set all colors to red
'''
colors = {
'BLACK': TextFormat('black'),
'DARK_GRAY': TextFormat('bold', 'black'),
'RED': TextFormat('red'),
'LIGHT_RED': TextFormat('bold', 'red'),
'GREEN': TextFormat('green'),
'LIGHT_GREEN': TextFormat('bold', 'green'),
'YELLOW': TextFormat('yellow'),
'LIGHT_YELLOW': TextFormat('bold', 'yellow'),
'BLUE': TextFormat('blue'),
'LIGHT_BLUE': TextFormat('bold', 'blue'),
'MAGENTA': TextFormat('magenta'),
'LIGHT_MAGENTA': TextFormat('bold', 'magenta'),
'CYAN': TextFormat('cyan'),
'LIGHT_CYAN': TextFormat('bold', 'cyan'),
'LIGHT_GRAY': TextFormat('white'),
'WHITE': TextFormat('bold', 'white'),
'DEFAULT_COLOR': TextFormat('default'),
'ENDC': TextFormat('reset'),
}
if theme:
colors.update(get_color_theme(theme))
if not use:
for color in colors:
colors[color] = ''
if isinstance(use, six.string_types):
# Try to set all of the colors to the passed color
if use in colors:
for color in colors:
# except for color reset
if color == 'ENDC':
continue
colors[color] = colors[use]
return colors | [
"def",
"get_colors",
"(",
"use",
"=",
"True",
",",
"theme",
"=",
"None",
")",
":",
"colors",
"=",
"{",
"'BLACK'",
":",
"TextFormat",
"(",
"'black'",
")",
",",
"'DARK_GRAY'",
":",
"TextFormat",
"(",
"'bold'",
",",
"'black'",
")",
",",
"'RED'",
":",
"T... | Return the colors as an easy to use dict. Pass `False` to deactivate all
colors by setting them to empty strings. Pass a string containing only the
name of a single color to be used in place of all colors. Examples:
.. code-block:: python
colors = get_colors() # enable all colors
no_colors = get_colors(False) # disable all colors
red_colors = get_colors('RED') # set all colors to red | [
"Return",
"the",
"colors",
"as",
"an",
"easy",
"to",
"use",
"dict",
".",
"Pass",
"False",
"to",
"deactivate",
"all",
"colors",
"by",
"setting",
"them",
"to",
"empty",
"strings",
".",
"Pass",
"a",
"string",
"containing",
"only",
"the",
"name",
"of",
"a",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/color.py#L44-L93 | train |
saltstack/salt | salt/states/zabbix_usergroup.py | present | def present(name, **kwargs):
'''
Creates new user group.
NOTE: This function accepts all standard user group properties: keyword argument names differ depending on your
zabbix version, see:
https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
.. versionadded:: 2016.3.0
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
make_new_thai_monks_usergroup:
zabbix_usergroup.present:
- name: 'Thai monks'
- gui_access: 1
- debug_mode: 0
- users_status: 0
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_usergroup_created = 'User group {0} created.'.format(name)
comment_usergroup_updated = 'User group {0} updated.'.format(name)
comment_usergroup_notcreated = 'Unable to create user group: {0}. '.format(name)
comment_usergroup_exists = 'User group {0} already exists.'.format(name)
changes_usergroup_created = {name: {'old': 'User group {0} does not exist.'.format(name),
'new': 'User group {0} created.'.format(name),
}
}
usergroup_exists = __salt__['zabbix.usergroup_exists'](name, **connection_args)
if usergroup_exists:
usergroup = __salt__['zabbix.usergroup_get'](name, **connection_args)[0]
usrgrpid = int(usergroup['usrgrpid'])
update_debug_mode = False
update_gui_access = False
update_users_status = False
update_rights = False
if 'debug_mode' in kwargs:
if int(kwargs['debug_mode']) != int(usergroup['debug_mode']):
update_debug_mode = True
if 'gui_access' in kwargs:
if int(kwargs['gui_access']) != int(usergroup['gui_access']):
update_gui_access = True
if 'rights' in kwargs:
# Older versions of Zabbix do not return the list of rights for the user group, handle this gracefully
try:
if usergroup['rights']:
# Make sure right values are strings so we can compare them with the current user group rights
for right in kwargs['rights']:
for key in right:
right[key] = six.text_type(right[key])
if sorted(kwargs['rights']) != sorted(usergroup['rights']):
update_rights = True
else:
update_rights = True
except KeyError:
# As we don't know the current permissions, overwrite them as provided in the state.
update_rights = True
if 'users_status' in kwargs:
if int(kwargs['users_status']) != int(usergroup['users_status']):
update_users_status = True
# Dry run, test=true mode
if __opts__['test']:
if usergroup_exists:
if update_debug_mode or update_gui_access or update_rights or update_users_status:
ret['result'] = None
ret['comment'] = comment_usergroup_updated
else:
ret['result'] = True
ret['comment'] = comment_usergroup_exists
else:
ret['result'] = None
ret['comment'] = comment_usergroup_created
return ret
error = []
if usergroup_exists:
if update_debug_mode or update_gui_access or update_rights or update_users_status:
ret['result'] = True
ret['comment'] = comment_usergroup_updated
if update_debug_mode:
updated_debug = __salt__['zabbix.usergroup_update'](usrgrpid,
debug_mode=kwargs['debug_mode'],
**connection_args)
if 'error' in updated_debug:
error.append(updated_debug['error'])
else:
ret['changes']['debug_mode'] = kwargs['debug_mode']
if update_gui_access:
updated_gui = __salt__['zabbix.usergroup_update'](usrgrpid,
gui_access=kwargs['gui_access'],
**connection_args)
if 'error' in updated_gui:
error.append(updated_gui['error'])
else:
ret['changes']['gui_access'] = kwargs['gui_access']
if update_rights:
updated_rights = __salt__['zabbix.usergroup_update'](usrgrpid,
rights=kwargs['rights'],
**connection_args)
if 'error' in updated_rights:
error.append(updated_rights['error'])
else:
ret['changes']['rights'] = kwargs['rights']
if update_users_status:
updated_status = __salt__['zabbix.usergroup_update'](usrgrpid,
users_status=kwargs['users_status'],
**connection_args)
if 'error' in updated_status:
error.append(updated_status['error'])
else:
ret['changes']['users_status'] = kwargs['users_status']
else:
ret['result'] = True
ret['comment'] = comment_usergroup_exists
else:
usergroup_create = __salt__['zabbix.usergroup_create'](name, **kwargs)
if 'error' not in usergroup_create:
ret['result'] = True
ret['comment'] = comment_usergroup_created
ret['changes'] = changes_usergroup_created
else:
ret['result'] = False
ret['comment'] = comment_usergroup_notcreated + six.text_type(usergroup_create['error'])
# error detected
if error:
ret['changes'] = {}
ret['result'] = False
ret['comment'] = six.text_type(error)
return ret | python | def present(name, **kwargs):
'''
Creates new user group.
NOTE: This function accepts all standard user group properties: keyword argument names differ depending on your
zabbix version, see:
https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
.. versionadded:: 2016.3.0
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
make_new_thai_monks_usergroup:
zabbix_usergroup.present:
- name: 'Thai monks'
- gui_access: 1
- debug_mode: 0
- users_status: 0
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_usergroup_created = 'User group {0} created.'.format(name)
comment_usergroup_updated = 'User group {0} updated.'.format(name)
comment_usergroup_notcreated = 'Unable to create user group: {0}. '.format(name)
comment_usergroup_exists = 'User group {0} already exists.'.format(name)
changes_usergroup_created = {name: {'old': 'User group {0} does not exist.'.format(name),
'new': 'User group {0} created.'.format(name),
}
}
usergroup_exists = __salt__['zabbix.usergroup_exists'](name, **connection_args)
if usergroup_exists:
usergroup = __salt__['zabbix.usergroup_get'](name, **connection_args)[0]
usrgrpid = int(usergroup['usrgrpid'])
update_debug_mode = False
update_gui_access = False
update_users_status = False
update_rights = False
if 'debug_mode' in kwargs:
if int(kwargs['debug_mode']) != int(usergroup['debug_mode']):
update_debug_mode = True
if 'gui_access' in kwargs:
if int(kwargs['gui_access']) != int(usergroup['gui_access']):
update_gui_access = True
if 'rights' in kwargs:
# Older versions of Zabbix do not return the list of rights for the user group, handle this gracefully
try:
if usergroup['rights']:
# Make sure right values are strings so we can compare them with the current user group rights
for right in kwargs['rights']:
for key in right:
right[key] = six.text_type(right[key])
if sorted(kwargs['rights']) != sorted(usergroup['rights']):
update_rights = True
else:
update_rights = True
except KeyError:
# As we don't know the current permissions, overwrite them as provided in the state.
update_rights = True
if 'users_status' in kwargs:
if int(kwargs['users_status']) != int(usergroup['users_status']):
update_users_status = True
# Dry run, test=true mode
if __opts__['test']:
if usergroup_exists:
if update_debug_mode or update_gui_access or update_rights or update_users_status:
ret['result'] = None
ret['comment'] = comment_usergroup_updated
else:
ret['result'] = True
ret['comment'] = comment_usergroup_exists
else:
ret['result'] = None
ret['comment'] = comment_usergroup_created
return ret
error = []
if usergroup_exists:
if update_debug_mode or update_gui_access or update_rights or update_users_status:
ret['result'] = True
ret['comment'] = comment_usergroup_updated
if update_debug_mode:
updated_debug = __salt__['zabbix.usergroup_update'](usrgrpid,
debug_mode=kwargs['debug_mode'],
**connection_args)
if 'error' in updated_debug:
error.append(updated_debug['error'])
else:
ret['changes']['debug_mode'] = kwargs['debug_mode']
if update_gui_access:
updated_gui = __salt__['zabbix.usergroup_update'](usrgrpid,
gui_access=kwargs['gui_access'],
**connection_args)
if 'error' in updated_gui:
error.append(updated_gui['error'])
else:
ret['changes']['gui_access'] = kwargs['gui_access']
if update_rights:
updated_rights = __salt__['zabbix.usergroup_update'](usrgrpid,
rights=kwargs['rights'],
**connection_args)
if 'error' in updated_rights:
error.append(updated_rights['error'])
else:
ret['changes']['rights'] = kwargs['rights']
if update_users_status:
updated_status = __salt__['zabbix.usergroup_update'](usrgrpid,
users_status=kwargs['users_status'],
**connection_args)
if 'error' in updated_status:
error.append(updated_status['error'])
else:
ret['changes']['users_status'] = kwargs['users_status']
else:
ret['result'] = True
ret['comment'] = comment_usergroup_exists
else:
usergroup_create = __salt__['zabbix.usergroup_create'](name, **kwargs)
if 'error' not in usergroup_create:
ret['result'] = True
ret['comment'] = comment_usergroup_created
ret['changes'] = changes_usergroup_created
else:
ret['result'] = False
ret['comment'] = comment_usergroup_notcreated + six.text_type(usergroup_create['error'])
# error detected
if error:
ret['changes'] = {}
ret['result'] = False
ret['comment'] = six.text_type(error)
return ret | [
"def",
"present",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_args",
"=",
"{",
"}",
"if",
"'_connection_user'",
"in",
"kwargs",
":",
"connection_args",
"[",
"'_connection_user'",
"]",
"=",
"kwargs",
"[",
"'_connection_user'",
"]",
"if",
"'_co... | Creates new user group.
NOTE: This function accepts all standard user group properties: keyword argument names differ depending on your
zabbix version, see:
https://www.zabbix.com/documentation/2.0/manual/appendix/api/usergroup/definitions#user_group
.. versionadded:: 2016.3.0
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
make_new_thai_monks_usergroup:
zabbix_usergroup.present:
- name: 'Thai monks'
- gui_access: 1
- debug_mode: 0
- users_status: 0 | [
"Creates",
"new",
"user",
"group",
".",
"NOTE",
":",
"This",
"function",
"accepts",
"all",
"standard",
"user",
"group",
"properties",
":",
"keyword",
"argument",
"names",
"differ",
"depending",
"on",
"your",
"zabbix",
"version",
"see",
":",
"https",
":",
"//... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_usergroup.py#L23-L182 | train |
saltstack/salt | salt/states/zabbix_usergroup.py | absent | def absent(name, **kwargs):
'''
Ensures that the user group does not exist, eventually delete user group.
.. versionadded:: 2016.3.0
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_thai_monks_usrgrp:
zabbix_usergroup.absent:
- name: 'Thai monks'
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_usergroup_deleted = 'User group {0} deleted.'.format(name)
comment_usergroup_notdeleted = 'Unable to delete user group: {0}. '.format(name)
comment_usergroup_notexists = 'User group {0} does not exist.'.format(name)
changes_usergroup_deleted = {name: {'old': 'User group {0} exists.'.format(name),
'new': 'User group {0} deleted.'.format(name),
}
}
usergroup_exists = __salt__['zabbix.usergroup_exists'](name, **connection_args)
# Dry run, test=true mode
if __opts__['test']:
if not usergroup_exists:
ret['result'] = True
ret['comment'] = comment_usergroup_notexists
else:
ret['result'] = None
ret['comment'] = comment_usergroup_deleted
return ret
usergroup_get = __salt__['zabbix.usergroup_get'](name, **connection_args)
if not usergroup_get:
ret['result'] = True
ret['comment'] = comment_usergroup_notexists
else:
try:
usrgrpid = usergroup_get[0]['usrgrpid']
usergroup_delete = __salt__['zabbix.usergroup_delete'](usrgrpid, **connection_args)
except KeyError:
usergroup_delete = False
if usergroup_delete and 'error' not in usergroup_delete:
ret['result'] = True
ret['comment'] = comment_usergroup_deleted
ret['changes'] = changes_usergroup_deleted
else:
ret['result'] = False
ret['comment'] = comment_usergroup_notdeleted + six.text_type(usergroup_delete['error'])
return ret | python | def absent(name, **kwargs):
'''
Ensures that the user group does not exist, eventually delete user group.
.. versionadded:: 2016.3.0
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_thai_monks_usrgrp:
zabbix_usergroup.absent:
- name: 'Thai monks'
'''
connection_args = {}
if '_connection_user' in kwargs:
connection_args['_connection_user'] = kwargs['_connection_user']
if '_connection_password' in kwargs:
connection_args['_connection_password'] = kwargs['_connection_password']
if '_connection_url' in kwargs:
connection_args['_connection_url'] = kwargs['_connection_url']
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
# Comment and change messages
comment_usergroup_deleted = 'User group {0} deleted.'.format(name)
comment_usergroup_notdeleted = 'Unable to delete user group: {0}. '.format(name)
comment_usergroup_notexists = 'User group {0} does not exist.'.format(name)
changes_usergroup_deleted = {name: {'old': 'User group {0} exists.'.format(name),
'new': 'User group {0} deleted.'.format(name),
}
}
usergroup_exists = __salt__['zabbix.usergroup_exists'](name, **connection_args)
# Dry run, test=true mode
if __opts__['test']:
if not usergroup_exists:
ret['result'] = True
ret['comment'] = comment_usergroup_notexists
else:
ret['result'] = None
ret['comment'] = comment_usergroup_deleted
return ret
usergroup_get = __salt__['zabbix.usergroup_get'](name, **connection_args)
if not usergroup_get:
ret['result'] = True
ret['comment'] = comment_usergroup_notexists
else:
try:
usrgrpid = usergroup_get[0]['usrgrpid']
usergroup_delete = __salt__['zabbix.usergroup_delete'](usrgrpid, **connection_args)
except KeyError:
usergroup_delete = False
if usergroup_delete and 'error' not in usergroup_delete:
ret['result'] = True
ret['comment'] = comment_usergroup_deleted
ret['changes'] = changes_usergroup_deleted
else:
ret['result'] = False
ret['comment'] = comment_usergroup_notdeleted + six.text_type(usergroup_delete['error'])
return ret | [
"def",
"absent",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"connection_args",
"=",
"{",
"}",
"if",
"'_connection_user'",
"in",
"kwargs",
":",
"connection_args",
"[",
"'_connection_user'",
"]",
"=",
"kwargs",
"[",
"'_connection_user'",
"]",
"if",
"'_con... | Ensures that the user group does not exist, eventually delete user group.
.. versionadded:: 2016.3.0
:param name: name of the user group
:param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring)
:param _connection_password: Optional - zabbix password (can also be set in opts or pillar, see module's docstring)
:param _connection_url: Optional - url of zabbix frontend (can also be set in opts, pillar, see module's docstring)
.. code-block:: yaml
delete_thai_monks_usrgrp:
zabbix_usergroup.absent:
- name: 'Thai monks' | [
"Ensures",
"that",
"the",
"user",
"group",
"does",
"not",
"exist",
"eventually",
"delete",
"user",
"group",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zabbix_usergroup.py#L185-L253 | train |
saltstack/salt | salt/modules/highstate_doc.py | _get_config | def _get_config(**kwargs):
'''
Return configuration
'''
config = {
'filter_id_regex': ['.*!doc_skip'],
'filter_function_regex': [],
'replace_text_regex': {},
'proccesser': 'highstate_doc.proccesser_markdown',
'max_render_file_size': 10000,
'note': None
}
if '__salt__' in globals():
config_key = '{0}.config'.format(__virtualname__)
config.update(__salt__['config.get'](config_key, {}))
# pylint: disable=C0201
for k in set(config.keys()) & set(kwargs.keys()):
config[k] = kwargs[k]
return config | python | def _get_config(**kwargs):
'''
Return configuration
'''
config = {
'filter_id_regex': ['.*!doc_skip'],
'filter_function_regex': [],
'replace_text_regex': {},
'proccesser': 'highstate_doc.proccesser_markdown',
'max_render_file_size': 10000,
'note': None
}
if '__salt__' in globals():
config_key = '{0}.config'.format(__virtualname__)
config.update(__salt__['config.get'](config_key, {}))
# pylint: disable=C0201
for k in set(config.keys()) & set(kwargs.keys()):
config[k] = kwargs[k]
return config | [
"def",
"_get_config",
"(",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"{",
"'filter_id_regex'",
":",
"[",
"'.*!doc_skip'",
"]",
",",
"'filter_function_regex'",
":",
"[",
"]",
",",
"'replace_text_regex'",
":",
"{",
"}",
",",
"'proccesser'",
":",
"'highstate... | Return configuration | [
"Return",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/highstate_doc.py#L365-L383 | train |
saltstack/salt | salt/modules/highstate_doc.py | read_file | def read_file(name):
'''
output the contents of a file:
this is a workaround if the cp.push module does not work.
https://github.com/saltstack/salt/issues/37133
help the master output the contents of a document
that might be saved on the minions filesystem.
.. code-block:: python
#!/bin/python
import os
import salt.client
s = salt.client.LocalClient()
o = s.cmd('*', 'highstate_doc.read_file', ['/root/README.md'])
for m in o:
d = o.get(m)
if d and not d.endswith('is not available.'):
# mkdir m
#directory = os.path.dirname(file_path)
if not os.path.exists(m):
os.makedirs(m)
with open(m + '/README.md','wb') as fin:
fin.write(d)
print('ADDED: ' + m + '/README.md')
'''
out = ''
try:
with salt.utils.files.fopen(name, 'r') as f:
out = salt.utils.stringutils.to_unicode(f.read())
except Exception as ex:
log.error(ex)
return None
return out | python | def read_file(name):
'''
output the contents of a file:
this is a workaround if the cp.push module does not work.
https://github.com/saltstack/salt/issues/37133
help the master output the contents of a document
that might be saved on the minions filesystem.
.. code-block:: python
#!/bin/python
import os
import salt.client
s = salt.client.LocalClient()
o = s.cmd('*', 'highstate_doc.read_file', ['/root/README.md'])
for m in o:
d = o.get(m)
if d and not d.endswith('is not available.'):
# mkdir m
#directory = os.path.dirname(file_path)
if not os.path.exists(m):
os.makedirs(m)
with open(m + '/README.md','wb') as fin:
fin.write(d)
print('ADDED: ' + m + '/README.md')
'''
out = ''
try:
with salt.utils.files.fopen(name, 'r') as f:
out = salt.utils.stringutils.to_unicode(f.read())
except Exception as ex:
log.error(ex)
return None
return out | [
"def",
"read_file",
"(",
"name",
")",
":",
"out",
"=",
"''",
"try",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"name",
",",
"'r'",
")",
"as",
"f",
":",
"out",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicod... | output the contents of a file:
this is a workaround if the cp.push module does not work.
https://github.com/saltstack/salt/issues/37133
help the master output the contents of a document
that might be saved on the minions filesystem.
.. code-block:: python
#!/bin/python
import os
import salt.client
s = salt.client.LocalClient()
o = s.cmd('*', 'highstate_doc.read_file', ['/root/README.md'])
for m in o:
d = o.get(m)
if d and not d.endswith('is not available.'):
# mkdir m
#directory = os.path.dirname(file_path)
if not os.path.exists(m):
os.makedirs(m)
with open(m + '/README.md','wb') as fin:
fin.write(d)
print('ADDED: ' + m + '/README.md') | [
"output",
"the",
"contents",
"of",
"a",
"file",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/highstate_doc.py#L386-L421 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.