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/esxi.py | ntp_configured | def ntp_configured(name,
service_running,
ntp_servers=None,
service_policy=None,
service_restart=False,
update_datetime=False):
'''
Ensures a host's NTP server configuration such as setting NTP servers, ensuring the
NTP daemon is running or stopped, or restarting the NTP daemon for the ESXi host.
name
Name of the state.
service_running
Ensures the running state of the ntp daemon for the host. Boolean value where
``True`` indicates that ntpd should be running and ``False`` indicates that it
should be stopped.
ntp_servers
A list of servers that should be added to the ESXi host's NTP configuration.
service_policy
The policy to set for the NTP service.
.. note::
When setting the service policy to ``off`` or ``on``, you *must* quote the
setting. If you don't, the yaml parser will set the string to a boolean,
which will cause trouble checking for stateful changes and will error when
trying to set the policy on the ESXi host.
service_restart
If set to ``True``, the ntp daemon will be restarted, regardless of its previous
running state. Default is ``False``.
update_datetime
If set to ``True``, the date/time on the given host will be updated to UTC.
Default setting is ``False``. This option should be used with caution since
network delays and execution delays can result in time skews.
Example:
.. code-block:: yaml
configure-host-ntp:
esxi.ntp_configured:
- service_running: True
- ntp_servers:
- 192.174.1.100
- 192.174.1.200
- service_policy: 'on'
- service_restart: True
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
ntpd = 'ntpd'
ntp_config = __salt__[esxi_cmd]('get_ntp_config').get(host)
ntp_running = __salt__[esxi_cmd]('get_service_running',
service_name=ntpd).get(host)
error = ntp_running.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ntp_running = ntp_running.get(ntpd)
# Configure NTP Servers for the Host
if ntp_servers and set(ntp_servers) != set(ntp_config):
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_ntp_config',
ntp_servers=ntp_servers).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Set changes dictionary for ntp_servers
ret['changes'].update({'ntp_servers':
{'old': ntp_config,
'new': ntp_servers}})
# Configure service_running state
if service_running != ntp_running:
# Only run the command if not using test=True
if not __opts__['test']:
# Start ntdp if service_running=True
if ntp_running is True:
response = __salt__[esxi_cmd]('service_start',
service_name=ntpd).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Stop ntpd if service_running=False
else:
response = __salt__[esxi_cmd]('service_stop',
service_name=ntpd).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_running':
{'old': ntp_running,
'new': service_running}})
# Configure service_policy
if service_policy:
current_service_policy = __salt__[esxi_cmd]('get_service_policy',
service_name=ntpd).get(host)
error = current_service_policy.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_service_policy = current_service_policy.get(ntpd)
if service_policy != current_service_policy:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_service_policy',
service_name=ntpd,
service_policy=service_policy).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_policy':
{'old': current_service_policy,
'new': service_policy}})
# Update datetime, if requested.
if update_datetime:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('update_host_datetime').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'update_datetime':
{'old': '',
'new': 'Host datetime was updated.'}})
# Restart ntp_service if service_restart=True
if service_restart:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('service_restart',
service_name=ntpd).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_restart':
{'old': '',
'new': 'NTP Daemon Restarted.'}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'NTP is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'NTP state will change.'
return ret | python | def ntp_configured(name,
service_running,
ntp_servers=None,
service_policy=None,
service_restart=False,
update_datetime=False):
'''
Ensures a host's NTP server configuration such as setting NTP servers, ensuring the
NTP daemon is running or stopped, or restarting the NTP daemon for the ESXi host.
name
Name of the state.
service_running
Ensures the running state of the ntp daemon for the host. Boolean value where
``True`` indicates that ntpd should be running and ``False`` indicates that it
should be stopped.
ntp_servers
A list of servers that should be added to the ESXi host's NTP configuration.
service_policy
The policy to set for the NTP service.
.. note::
When setting the service policy to ``off`` or ``on``, you *must* quote the
setting. If you don't, the yaml parser will set the string to a boolean,
which will cause trouble checking for stateful changes and will error when
trying to set the policy on the ESXi host.
service_restart
If set to ``True``, the ntp daemon will be restarted, regardless of its previous
running state. Default is ``False``.
update_datetime
If set to ``True``, the date/time on the given host will be updated to UTC.
Default setting is ``False``. This option should be used with caution since
network delays and execution delays can result in time skews.
Example:
.. code-block:: yaml
configure-host-ntp:
esxi.ntp_configured:
- service_running: True
- ntp_servers:
- 192.174.1.100
- 192.174.1.200
- service_policy: 'on'
- service_restart: True
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
ntpd = 'ntpd'
ntp_config = __salt__[esxi_cmd]('get_ntp_config').get(host)
ntp_running = __salt__[esxi_cmd]('get_service_running',
service_name=ntpd).get(host)
error = ntp_running.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ntp_running = ntp_running.get(ntpd)
# Configure NTP Servers for the Host
if ntp_servers and set(ntp_servers) != set(ntp_config):
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_ntp_config',
ntp_servers=ntp_servers).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Set changes dictionary for ntp_servers
ret['changes'].update({'ntp_servers':
{'old': ntp_config,
'new': ntp_servers}})
# Configure service_running state
if service_running != ntp_running:
# Only run the command if not using test=True
if not __opts__['test']:
# Start ntdp if service_running=True
if ntp_running is True:
response = __salt__[esxi_cmd]('service_start',
service_name=ntpd).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Stop ntpd if service_running=False
else:
response = __salt__[esxi_cmd]('service_stop',
service_name=ntpd).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_running':
{'old': ntp_running,
'new': service_running}})
# Configure service_policy
if service_policy:
current_service_policy = __salt__[esxi_cmd]('get_service_policy',
service_name=ntpd).get(host)
error = current_service_policy.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_service_policy = current_service_policy.get(ntpd)
if service_policy != current_service_policy:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_service_policy',
service_name=ntpd,
service_policy=service_policy).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_policy':
{'old': current_service_policy,
'new': service_policy}})
# Update datetime, if requested.
if update_datetime:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('update_host_datetime').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'update_datetime':
{'old': '',
'new': 'Host datetime was updated.'}})
# Restart ntp_service if service_restart=True
if service_restart:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('service_restart',
service_name=ntpd).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_restart':
{'old': '',
'new': 'NTP Daemon Restarted.'}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'NTP is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'NTP state will change.'
return ret | [
"def",
"ntp_configured",
"(",
"name",
",",
"service_running",
",",
"ntp_servers",
"=",
"None",
",",
"service_policy",
"=",
"None",
",",
"service_restart",
"=",
"False",
",",
"update_datetime",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
... | Ensures a host's NTP server configuration such as setting NTP servers, ensuring the
NTP daemon is running or stopped, or restarting the NTP daemon for the ESXi host.
name
Name of the state.
service_running
Ensures the running state of the ntp daemon for the host. Boolean value where
``True`` indicates that ntpd should be running and ``False`` indicates that it
should be stopped.
ntp_servers
A list of servers that should be added to the ESXi host's NTP configuration.
service_policy
The policy to set for the NTP service.
.. note::
When setting the service policy to ``off`` or ``on``, you *must* quote the
setting. If you don't, the yaml parser will set the string to a boolean,
which will cause trouble checking for stateful changes and will error when
trying to set the policy on the ESXi host.
service_restart
If set to ``True``, the ntp daemon will be restarted, regardless of its previous
running state. Default is ``False``.
update_datetime
If set to ``True``, the date/time on the given host will be updated to UTC.
Default setting is ``False``. This option should be used with caution since
network delays and execution delays can result in time skews.
Example:
.. code-block:: yaml
configure-host-ntp:
esxi.ntp_configured:
- service_running: True
- ntp_servers:
- 192.174.1.100
- 192.174.1.200
- service_policy: 'on'
- service_restart: True | [
"Ensures",
"a",
"host",
"s",
"NTP",
"server",
"configuration",
"such",
"as",
"setting",
"NTP",
"servers",
"ensuring",
"the",
"NTP",
"daemon",
"is",
"running",
"or",
"stopped",
"or",
"restarting",
"the",
"NTP",
"daemon",
"for",
"the",
"ESXi",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L326-L497 | train |
saltstack/salt | salt/states/esxi.py | vmotion_configured | def vmotion_configured(name, enabled, device='vmk0'):
'''
Configures a host's VMotion properties such as enabling VMotion and setting
the device VirtualNic that VMotion will use.
name
Name of the state.
enabled
Ensures whether or not VMotion should be enabled on a host as a boolean
value where ``True`` indicates that VMotion should be enabled and ``False``
indicates that VMotion should be disabled.
device
The device that uniquely identifies the VirtualNic that will be used for
VMotion for the host. Defaults to ``vmk0``.
Example:
.. code-block:: yaml
configure-vmotion:
esxi.vmotion_configured:
- enabled: True
- device: sample-device
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
current_vmotion_enabled = __salt__[esxi_cmd]('get_vmotion_enabled').get(host)
current_vmotion_enabled = current_vmotion_enabled.get('VMotion Enabled')
# Configure VMotion Enabled state, if changed.
if enabled != current_vmotion_enabled:
# Only run the command if not using test=True
if not __opts__['test']:
# Enable VMotion if enabled=True
if enabled is True:
response = __salt__[esxi_cmd]('vmotion_enable',
device=device).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Disable VMotion if enabled=False
else:
response = __salt__[esxi_cmd]('vmotion_disable').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'enabled':
{'old': current_vmotion_enabled,
'new': enabled}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'VMotion configuration is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'VMotion configuration will change.'
return ret | python | def vmotion_configured(name, enabled, device='vmk0'):
'''
Configures a host's VMotion properties such as enabling VMotion and setting
the device VirtualNic that VMotion will use.
name
Name of the state.
enabled
Ensures whether or not VMotion should be enabled on a host as a boolean
value where ``True`` indicates that VMotion should be enabled and ``False``
indicates that VMotion should be disabled.
device
The device that uniquely identifies the VirtualNic that will be used for
VMotion for the host. Defaults to ``vmk0``.
Example:
.. code-block:: yaml
configure-vmotion:
esxi.vmotion_configured:
- enabled: True
- device: sample-device
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
current_vmotion_enabled = __salt__[esxi_cmd]('get_vmotion_enabled').get(host)
current_vmotion_enabled = current_vmotion_enabled.get('VMotion Enabled')
# Configure VMotion Enabled state, if changed.
if enabled != current_vmotion_enabled:
# Only run the command if not using test=True
if not __opts__['test']:
# Enable VMotion if enabled=True
if enabled is True:
response = __salt__[esxi_cmd]('vmotion_enable',
device=device).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Disable VMotion if enabled=False
else:
response = __salt__[esxi_cmd]('vmotion_disable').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'enabled':
{'old': current_vmotion_enabled,
'new': enabled}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'VMotion configuration is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'VMotion configuration will change.'
return ret | [
"def",
"vmotion_configured",
"(",
"name",
",",
"enabled",
",",
"device",
"=",
"'vmk0'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"esxi_cmd",
"=... | Configures a host's VMotion properties such as enabling VMotion and setting
the device VirtualNic that VMotion will use.
name
Name of the state.
enabled
Ensures whether or not VMotion should be enabled on a host as a boolean
value where ``True`` indicates that VMotion should be enabled and ``False``
indicates that VMotion should be disabled.
device
The device that uniquely identifies the VirtualNic that will be used for
VMotion for the host. Defaults to ``vmk0``.
Example:
.. code-block:: yaml
configure-vmotion:
esxi.vmotion_configured:
- enabled: True
- device: sample-device | [
"Configures",
"a",
"host",
"s",
"VMotion",
"properties",
"such",
"as",
"enabling",
"VMotion",
"and",
"setting",
"the",
"device",
"VirtualNic",
"that",
"VMotion",
"will",
"use",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L500-L569 | train |
saltstack/salt | salt/states/esxi.py | vsan_configured | def vsan_configured(name, enabled, add_disks_to_vsan=False):
'''
Configures a host's VSAN properties such as enabling or disabling VSAN, or
adding VSAN-eligible disks to the VSAN system for the host.
name
Name of the state.
enabled
Ensures whether or not VSAN should be enabled on a host as a boolean
value where ``True`` indicates that VSAN should be enabled and ``False``
indicates that VSAN should be disabled.
add_disks_to_vsan
If set to ``True``, any VSAN-eligible disks for the given host will be added
to the host's VSAN system. Default is ``False``.
Example:
.. code-block:: yaml
configure-host-vsan:
esxi.vsan_configured:
- enabled: True
- add_disks_to_vsan: True
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
current_vsan_enabled = __salt__[esxi_cmd]('get_vsan_enabled').get(host)
error = current_vsan_enabled.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_vsan_enabled = current_vsan_enabled.get('VSAN Enabled')
# Configure VSAN Enabled state, if changed.
if enabled != current_vsan_enabled:
# Only run the command if not using test=True
if not __opts__['test']:
# Enable VSAN if enabled=True
if enabled is True:
response = __salt__[esxi_cmd]('vsan_enable').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Disable VSAN if enabled=False
else:
response = __salt__[esxi_cmd]('vsan_disable').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'enabled':
{'old': current_vsan_enabled,
'new': enabled}})
# Add any eligible disks to VSAN, if requested.
if add_disks_to_vsan:
current_eligible_disks = __salt__[esxi_cmd]('get_vsan_eligible_disks').get(host)
error = current_eligible_disks.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
disks = current_eligible_disks.get('Eligible')
if disks and isinstance(disks, list):
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('vsan_add_disks').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'add_disks_to_vsan':
{'old': '',
'new': disks}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'VSAN configuration is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'VSAN configuration will change.'
return ret | python | def vsan_configured(name, enabled, add_disks_to_vsan=False):
'''
Configures a host's VSAN properties such as enabling or disabling VSAN, or
adding VSAN-eligible disks to the VSAN system for the host.
name
Name of the state.
enabled
Ensures whether or not VSAN should be enabled on a host as a boolean
value where ``True`` indicates that VSAN should be enabled and ``False``
indicates that VSAN should be disabled.
add_disks_to_vsan
If set to ``True``, any VSAN-eligible disks for the given host will be added
to the host's VSAN system. Default is ``False``.
Example:
.. code-block:: yaml
configure-host-vsan:
esxi.vsan_configured:
- enabled: True
- add_disks_to_vsan: True
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
current_vsan_enabled = __salt__[esxi_cmd]('get_vsan_enabled').get(host)
error = current_vsan_enabled.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_vsan_enabled = current_vsan_enabled.get('VSAN Enabled')
# Configure VSAN Enabled state, if changed.
if enabled != current_vsan_enabled:
# Only run the command if not using test=True
if not __opts__['test']:
# Enable VSAN if enabled=True
if enabled is True:
response = __salt__[esxi_cmd]('vsan_enable').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Disable VSAN if enabled=False
else:
response = __salt__[esxi_cmd]('vsan_disable').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'enabled':
{'old': current_vsan_enabled,
'new': enabled}})
# Add any eligible disks to VSAN, if requested.
if add_disks_to_vsan:
current_eligible_disks = __salt__[esxi_cmd]('get_vsan_eligible_disks').get(host)
error = current_eligible_disks.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
disks = current_eligible_disks.get('Eligible')
if disks and isinstance(disks, list):
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('vsan_add_disks').get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'add_disks_to_vsan':
{'old': '',
'new': disks}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'VSAN configuration is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'VSAN configuration will change.'
return ret | [
"def",
"vsan_configured",
"(",
"name",
",",
"enabled",
",",
"add_disks_to_vsan",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"esxi_cmd... | Configures a host's VSAN properties such as enabling or disabling VSAN, or
adding VSAN-eligible disks to the VSAN system for the host.
name
Name of the state.
enabled
Ensures whether or not VSAN should be enabled on a host as a boolean
value where ``True`` indicates that VSAN should be enabled and ``False``
indicates that VSAN should be disabled.
add_disks_to_vsan
If set to ``True``, any VSAN-eligible disks for the given host will be added
to the host's VSAN system. Default is ``False``.
Example:
.. code-block:: yaml
configure-host-vsan:
esxi.vsan_configured:
- enabled: True
- add_disks_to_vsan: True | [
"Configures",
"a",
"host",
"s",
"VSAN",
"properties",
"such",
"as",
"enabling",
"or",
"disabling",
"VSAN",
"or",
"adding",
"VSAN",
"-",
"eligible",
"disks",
"to",
"the",
"VSAN",
"system",
"for",
"the",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L572-L666 | train |
saltstack/salt | salt/states/esxi.py | ssh_configured | def ssh_configured(name,
service_running,
ssh_key=None,
ssh_key_file=None,
service_policy=None,
service_restart=False,
certificate_verify=False):
'''
Manage the SSH configuration for a host including whether or not SSH is running or
the presence of a given SSH key. Note: Only one ssh key can be uploaded for root.
Uploading a second key will replace any existing key.
name
Name of the state.
service_running
Ensures whether or not the SSH service should be running on a host. Represented
as a boolean value where ``True`` indicates that SSH should be running and
``False`` indicates that SSH should stopped.
In order to update SSH keys, the SSH service must be running.
ssh_key
Public SSH key to added to the authorized_keys file on the ESXi host. You can
use ``ssh_key`` or ``ssh_key_file``, but not both.
ssh_key_file
File containing the public SSH key to be added to the authorized_keys file on
the ESXi host. You can use ``ssh_key_file`` or ``ssh_key``, but not both.
service_policy
The policy to set for the NTP service.
.. note::
When setting the service policy to ``off`` or ``on``, you *must* quote the
setting. If you don't, the yaml parser will set the string to a boolean,
which will cause trouble checking for stateful changes and will error when
trying to set the policy on the ESXi host.
service_restart
If set to ``True``, the SSH service will be restarted, regardless of its
previous running state. Default is ``False``.
certificate_verify
If set to ``True``, the SSL connection must present a valid certificate.
Default is ``False``.
Example:
.. code-block:: yaml
configure-host-ssh:
esxi.ssh_configured:
- service_running: True
- ssh_key_file: /etc/salt/ssh_keys/my_key.pub
- service_policy: 'on'
- service_restart: True
- certificate_verify: True
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
ssh = 'ssh'
ssh_running = __salt__[esxi_cmd]('get_service_running',
service_name=ssh).get(host)
error = ssh_running.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ssh_running = ssh_running.get(ssh)
# Configure SSH service_running state, if changed.
if service_running != ssh_running:
# Only actually run the command if not using test=True
if not __opts__['test']:
# Start SSH if service_running=True
if service_running is True:
enable = __salt__[esxi_cmd]('service_start',
service_name=ssh).get(host)
error = enable.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Disable SSH if service_running=False
else:
disable = __salt__[esxi_cmd]('service_stop',
service_name=ssh).get(host)
error = disable.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_running':
{'old': ssh_running,
'new': service_running}})
# If uploading an SSH key or SSH key file, see if there's a current
# SSH key and compare the current key to the key set in the state.
current_ssh_key, ssh_key_changed = None, False
if ssh_key or ssh_key_file:
current_ssh_key = __salt__[esxi_cmd]('get_ssh_key',
certificate_verify=certificate_verify)
error = current_ssh_key.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_ssh_key = current_ssh_key.get('key')
if current_ssh_key:
clean_current_key = _strip_key(current_ssh_key).split(' ')
if not ssh_key:
ssh_key = ''
# Open ssh key file and read in contents to create one key string
with salt.utils.files.fopen(ssh_key_file, 'r') as key_file:
for line in key_file:
if line.startswith('#'):
# Commented line
continue
ssh_key = ssh_key + line
clean_ssh_key = _strip_key(ssh_key).split(' ')
# Check that the first two list items of clean key lists are equal.
if clean_current_key[0] != clean_ssh_key[0] or clean_current_key[1] != clean_ssh_key[1]:
ssh_key_changed = True
else:
# If current_ssh_key is None, but we're setting a new key with
# either ssh_key or ssh_key_file, then we need to flag the change.
ssh_key_changed = True
# Upload SSH key, if changed.
if ssh_key_changed:
if not __opts__['test']:
# Upload key
response = __salt__[esxi_cmd]('upload_ssh_key',
ssh_key=ssh_key,
ssh_key_file=ssh_key_file,
certificate_verify=certificate_verify)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'SSH Key':
{'old': current_ssh_key,
'new': ssh_key if ssh_key else ssh_key_file}})
# Configure service_policy
if service_policy:
current_service_policy = __salt__[esxi_cmd]('get_service_policy',
service_name=ssh).get(host)
error = current_service_policy.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_service_policy = current_service_policy.get(ssh)
if service_policy != current_service_policy:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_service_policy',
service_name=ssh,
service_policy=service_policy).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_policy':
{'old': current_service_policy,
'new': service_policy}})
# Restart ssh_service if service_restart=True
if service_restart:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('service_restart',
service_name=ssh).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_restart':
{'old': '',
'new': 'SSH service restarted.'}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'SSH service is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'SSH service state will change.'
return ret | python | def ssh_configured(name,
service_running,
ssh_key=None,
ssh_key_file=None,
service_policy=None,
service_restart=False,
certificate_verify=False):
'''
Manage the SSH configuration for a host including whether or not SSH is running or
the presence of a given SSH key. Note: Only one ssh key can be uploaded for root.
Uploading a second key will replace any existing key.
name
Name of the state.
service_running
Ensures whether or not the SSH service should be running on a host. Represented
as a boolean value where ``True`` indicates that SSH should be running and
``False`` indicates that SSH should stopped.
In order to update SSH keys, the SSH service must be running.
ssh_key
Public SSH key to added to the authorized_keys file on the ESXi host. You can
use ``ssh_key`` or ``ssh_key_file``, but not both.
ssh_key_file
File containing the public SSH key to be added to the authorized_keys file on
the ESXi host. You can use ``ssh_key_file`` or ``ssh_key``, but not both.
service_policy
The policy to set for the NTP service.
.. note::
When setting the service policy to ``off`` or ``on``, you *must* quote the
setting. If you don't, the yaml parser will set the string to a boolean,
which will cause trouble checking for stateful changes and will error when
trying to set the policy on the ESXi host.
service_restart
If set to ``True``, the SSH service will be restarted, regardless of its
previous running state. Default is ``False``.
certificate_verify
If set to ``True``, the SSL connection must present a valid certificate.
Default is ``False``.
Example:
.. code-block:: yaml
configure-host-ssh:
esxi.ssh_configured:
- service_running: True
- ssh_key_file: /etc/salt/ssh_keys/my_key.pub
- service_policy: 'on'
- service_restart: True
- certificate_verify: True
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
ssh = 'ssh'
ssh_running = __salt__[esxi_cmd]('get_service_running',
service_name=ssh).get(host)
error = ssh_running.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ssh_running = ssh_running.get(ssh)
# Configure SSH service_running state, if changed.
if service_running != ssh_running:
# Only actually run the command if not using test=True
if not __opts__['test']:
# Start SSH if service_running=True
if service_running is True:
enable = __salt__[esxi_cmd]('service_start',
service_name=ssh).get(host)
error = enable.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Disable SSH if service_running=False
else:
disable = __salt__[esxi_cmd]('service_stop',
service_name=ssh).get(host)
error = disable.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_running':
{'old': ssh_running,
'new': service_running}})
# If uploading an SSH key or SSH key file, see if there's a current
# SSH key and compare the current key to the key set in the state.
current_ssh_key, ssh_key_changed = None, False
if ssh_key or ssh_key_file:
current_ssh_key = __salt__[esxi_cmd]('get_ssh_key',
certificate_verify=certificate_verify)
error = current_ssh_key.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_ssh_key = current_ssh_key.get('key')
if current_ssh_key:
clean_current_key = _strip_key(current_ssh_key).split(' ')
if not ssh_key:
ssh_key = ''
# Open ssh key file and read in contents to create one key string
with salt.utils.files.fopen(ssh_key_file, 'r') as key_file:
for line in key_file:
if line.startswith('#'):
# Commented line
continue
ssh_key = ssh_key + line
clean_ssh_key = _strip_key(ssh_key).split(' ')
# Check that the first two list items of clean key lists are equal.
if clean_current_key[0] != clean_ssh_key[0] or clean_current_key[1] != clean_ssh_key[1]:
ssh_key_changed = True
else:
# If current_ssh_key is None, but we're setting a new key with
# either ssh_key or ssh_key_file, then we need to flag the change.
ssh_key_changed = True
# Upload SSH key, if changed.
if ssh_key_changed:
if not __opts__['test']:
# Upload key
response = __salt__[esxi_cmd]('upload_ssh_key',
ssh_key=ssh_key,
ssh_key_file=ssh_key_file,
certificate_verify=certificate_verify)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'SSH Key':
{'old': current_ssh_key,
'new': ssh_key if ssh_key else ssh_key_file}})
# Configure service_policy
if service_policy:
current_service_policy = __salt__[esxi_cmd]('get_service_policy',
service_name=ssh).get(host)
error = current_service_policy.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_service_policy = current_service_policy.get(ssh)
if service_policy != current_service_policy:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_service_policy',
service_name=ssh,
service_policy=service_policy).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_policy':
{'old': current_service_policy,
'new': service_policy}})
# Restart ssh_service if service_restart=True
if service_restart:
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('service_restart',
service_name=ssh).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
ret['changes'].update({'service_restart':
{'old': '',
'new': 'SSH service restarted.'}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'SSH service is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'SSH service state will change.'
return ret | [
"def",
"ssh_configured",
"(",
"name",
",",
"service_running",
",",
"ssh_key",
"=",
"None",
",",
"ssh_key_file",
"=",
"None",
",",
"service_policy",
"=",
"None",
",",
"service_restart",
"=",
"False",
",",
"certificate_verify",
"=",
"False",
")",
":",
"ret",
"... | Manage the SSH configuration for a host including whether or not SSH is running or
the presence of a given SSH key. Note: Only one ssh key can be uploaded for root.
Uploading a second key will replace any existing key.
name
Name of the state.
service_running
Ensures whether or not the SSH service should be running on a host. Represented
as a boolean value where ``True`` indicates that SSH should be running and
``False`` indicates that SSH should stopped.
In order to update SSH keys, the SSH service must be running.
ssh_key
Public SSH key to added to the authorized_keys file on the ESXi host. You can
use ``ssh_key`` or ``ssh_key_file``, but not both.
ssh_key_file
File containing the public SSH key to be added to the authorized_keys file on
the ESXi host. You can use ``ssh_key_file`` or ``ssh_key``, but not both.
service_policy
The policy to set for the NTP service.
.. note::
When setting the service policy to ``off`` or ``on``, you *must* quote the
setting. If you don't, the yaml parser will set the string to a boolean,
which will cause trouble checking for stateful changes and will error when
trying to set the policy on the ESXi host.
service_restart
If set to ``True``, the SSH service will be restarted, regardless of its
previous running state. Default is ``False``.
certificate_verify
If set to ``True``, the SSL connection must present a valid certificate.
Default is ``False``.
Example:
.. code-block:: yaml
configure-host-ssh:
esxi.ssh_configured:
- service_running: True
- ssh_key_file: /etc/salt/ssh_keys/my_key.pub
- service_policy: 'on'
- service_restart: True
- certificate_verify: True | [
"Manage",
"the",
"SSH",
"configuration",
"for",
"a",
"host",
"including",
"whether",
"or",
"not",
"SSH",
"is",
"running",
"or",
"the",
"presence",
"of",
"a",
"given",
"SSH",
"key",
".",
"Note",
":",
"Only",
"one",
"ssh",
"key",
"can",
"be",
"uploaded",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L669-L866 | train |
saltstack/salt | salt/states/esxi.py | syslog_configured | def syslog_configured(name,
syslog_configs,
firewall=True,
reset_service=True,
reset_syslog_config=False,
reset_configs=None):
'''
Ensures the specified syslog configuration parameters. By default,
this state will reset the syslog service after any new or changed
parameters are set successfully.
name
Name of the state.
syslog_configs
Name of parameter to set (corresponds to the command line switch for
esxcli without the double dashes (--))
Valid syslog_config values are ``logdir``, ``loghost``, ``logdir-unique``,
``default-rotate``, ``default-size``, and ``default-timeout``.
Each syslog_config option also needs a configuration value to set.
For example, ``loghost`` requires URLs or IP addresses to use for
logging. Multiple log servers can be specified by listing them,
comma-separated, but without spaces before or after commas
(reference: https://blogs.vmware.com/vsphere/2012/04/configuring-multiple-syslog-servers-for-esxi-5.html)
firewall
Enable the firewall rule set for syslog. Defaults to ``True``.
reset_service
After a successful parameter set, reset the service. Defaults to ``True``.
reset_syslog_config
Resets the syslog service to it's default settings. Defaults to ``False``.
If set to ``True``, default settings defined by the list of syslog configs
in ``reset_configs`` will be reset before running any other syslog settings.
reset_configs
A comma-delimited list of parameters to reset. Only runs if
``reset_syslog_config`` is set to ``True``. If ``reset_syslog_config`` is set
to ``True``, but no syslog configs are listed in ``reset_configs``, then
``reset_configs`` will be set to ``all`` by default.
See ``syslog_configs`` parameter above for a list of valid options.
Example:
.. code-block:: yaml
configure-host-syslog:
esxi.syslog_configured:
- syslog_configs:
loghost: ssl://localhost:5432,tcp://10.1.0.1:1514
default-timeout: 120
- firewall: True
- reset_service: True
- reset_syslog_config: True
- reset_configs: loghost,default-timeout
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
if reset_syslog_config:
if not reset_configs:
reset_configs = 'all'
# Only run the command if not using test=True
if not __opts__['test']:
reset = __salt__[esxi_cmd]('reset_syslog_config',
syslog_config=reset_configs).get(host)
for key, val in six.iteritems(reset):
if isinstance(val, bool):
continue
if not val.get('success'):
msg = val.get('message')
if not msg:
msg = 'There was an error resetting a syslog config \'{0}\'.' \
'Please check debug logs.'.format(val)
ret['comment'] = 'Error: {0}'.format(msg)
return ret
ret['changes'].update({'reset_syslog_config':
{'old': '',
'new': reset_configs}})
current_firewall = __salt__[esxi_cmd]('get_firewall_status').get(host)
error = current_firewall.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_firewall = current_firewall.get('rulesets').get('syslog')
if current_firewall != firewall:
# Only run the command if not using test=True
if not __opts__['test']:
enabled = __salt__[esxi_cmd]('enable_firewall_ruleset',
ruleset_enable=firewall,
ruleset_name='syslog').get(host)
if enabled.get('retcode') != 0:
err = enabled.get('stderr')
out = enabled.get('stdout')
ret['comment'] = 'Error: {0}'.format(err if err else out)
return ret
ret['changes'].update({'firewall':
{'old': current_firewall,
'new': firewall}})
current_syslog_config = __salt__[esxi_cmd]('get_syslog_config').get(host)
for key, val in six.iteritems(syslog_configs):
# The output of get_syslog_config has different keys than the keys
# Used to set syslog_config values. We need to look them up first.
try:
lookup_key = _lookup_syslog_config(key)
except KeyError:
ret['comment'] = '\'{0}\' is not a valid config variable.'.format(key)
return ret
current_val = current_syslog_config[lookup_key]
if six.text_type(current_val) != six.text_type(val):
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_syslog_config',
syslog_config=key,
config_value=val,
firewall=firewall,
reset_service=reset_service).get(host)
success = response.get(key).get('success')
if not success:
msg = response.get(key).get('message')
if not msg:
msg = 'There was an error setting syslog config \'{0}\'. ' \
'Please check debug logs.'.format(key)
ret['comment'] = msg
return ret
if not ret['changes'].get('syslog_config'):
ret['changes'].update({'syslog_config': {}})
ret['changes']['syslog_config'].update({key:
{'old': current_val,
'new': val}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'Syslog is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Syslog state will change.'
return ret | python | def syslog_configured(name,
syslog_configs,
firewall=True,
reset_service=True,
reset_syslog_config=False,
reset_configs=None):
'''
Ensures the specified syslog configuration parameters. By default,
this state will reset the syslog service after any new or changed
parameters are set successfully.
name
Name of the state.
syslog_configs
Name of parameter to set (corresponds to the command line switch for
esxcli without the double dashes (--))
Valid syslog_config values are ``logdir``, ``loghost``, ``logdir-unique``,
``default-rotate``, ``default-size``, and ``default-timeout``.
Each syslog_config option also needs a configuration value to set.
For example, ``loghost`` requires URLs or IP addresses to use for
logging. Multiple log servers can be specified by listing them,
comma-separated, but without spaces before or after commas
(reference: https://blogs.vmware.com/vsphere/2012/04/configuring-multiple-syslog-servers-for-esxi-5.html)
firewall
Enable the firewall rule set for syslog. Defaults to ``True``.
reset_service
After a successful parameter set, reset the service. Defaults to ``True``.
reset_syslog_config
Resets the syslog service to it's default settings. Defaults to ``False``.
If set to ``True``, default settings defined by the list of syslog configs
in ``reset_configs`` will be reset before running any other syslog settings.
reset_configs
A comma-delimited list of parameters to reset. Only runs if
``reset_syslog_config`` is set to ``True``. If ``reset_syslog_config`` is set
to ``True``, but no syslog configs are listed in ``reset_configs``, then
``reset_configs`` will be set to ``all`` by default.
See ``syslog_configs`` parameter above for a list of valid options.
Example:
.. code-block:: yaml
configure-host-syslog:
esxi.syslog_configured:
- syslog_configs:
loghost: ssl://localhost:5432,tcp://10.1.0.1:1514
default-timeout: 120
- firewall: True
- reset_service: True
- reset_syslog_config: True
- reset_configs: loghost,default-timeout
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
host = __pillar__['proxy']['host']
if reset_syslog_config:
if not reset_configs:
reset_configs = 'all'
# Only run the command if not using test=True
if not __opts__['test']:
reset = __salt__[esxi_cmd]('reset_syslog_config',
syslog_config=reset_configs).get(host)
for key, val in six.iteritems(reset):
if isinstance(val, bool):
continue
if not val.get('success'):
msg = val.get('message')
if not msg:
msg = 'There was an error resetting a syslog config \'{0}\'.' \
'Please check debug logs.'.format(val)
ret['comment'] = 'Error: {0}'.format(msg)
return ret
ret['changes'].update({'reset_syslog_config':
{'old': '',
'new': reset_configs}})
current_firewall = __salt__[esxi_cmd]('get_firewall_status').get(host)
error = current_firewall.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_firewall = current_firewall.get('rulesets').get('syslog')
if current_firewall != firewall:
# Only run the command if not using test=True
if not __opts__['test']:
enabled = __salt__[esxi_cmd]('enable_firewall_ruleset',
ruleset_enable=firewall,
ruleset_name='syslog').get(host)
if enabled.get('retcode') != 0:
err = enabled.get('stderr')
out = enabled.get('stdout')
ret['comment'] = 'Error: {0}'.format(err if err else out)
return ret
ret['changes'].update({'firewall':
{'old': current_firewall,
'new': firewall}})
current_syslog_config = __salt__[esxi_cmd]('get_syslog_config').get(host)
for key, val in six.iteritems(syslog_configs):
# The output of get_syslog_config has different keys than the keys
# Used to set syslog_config values. We need to look them up first.
try:
lookup_key = _lookup_syslog_config(key)
except KeyError:
ret['comment'] = '\'{0}\' is not a valid config variable.'.format(key)
return ret
current_val = current_syslog_config[lookup_key]
if six.text_type(current_val) != six.text_type(val):
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('set_syslog_config',
syslog_config=key,
config_value=val,
firewall=firewall,
reset_service=reset_service).get(host)
success = response.get(key).get('success')
if not success:
msg = response.get(key).get('message')
if not msg:
msg = 'There was an error setting syslog config \'{0}\'. ' \
'Please check debug logs.'.format(key)
ret['comment'] = msg
return ret
if not ret['changes'].get('syslog_config'):
ret['changes'].update({'syslog_config': {}})
ret['changes']['syslog_config'].update({key:
{'old': current_val,
'new': val}})
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'Syslog is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Syslog state will change.'
return ret | [
"def",
"syslog_configured",
"(",
"name",
",",
"syslog_configs",
",",
"firewall",
"=",
"True",
",",
"reset_service",
"=",
"True",
",",
"reset_syslog_config",
"=",
"False",
",",
"reset_configs",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
... | Ensures the specified syslog configuration parameters. By default,
this state will reset the syslog service after any new or changed
parameters are set successfully.
name
Name of the state.
syslog_configs
Name of parameter to set (corresponds to the command line switch for
esxcli without the double dashes (--))
Valid syslog_config values are ``logdir``, ``loghost``, ``logdir-unique``,
``default-rotate``, ``default-size``, and ``default-timeout``.
Each syslog_config option also needs a configuration value to set.
For example, ``loghost`` requires URLs or IP addresses to use for
logging. Multiple log servers can be specified by listing them,
comma-separated, but without spaces before or after commas
(reference: https://blogs.vmware.com/vsphere/2012/04/configuring-multiple-syslog-servers-for-esxi-5.html)
firewall
Enable the firewall rule set for syslog. Defaults to ``True``.
reset_service
After a successful parameter set, reset the service. Defaults to ``True``.
reset_syslog_config
Resets the syslog service to it's default settings. Defaults to ``False``.
If set to ``True``, default settings defined by the list of syslog configs
in ``reset_configs`` will be reset before running any other syslog settings.
reset_configs
A comma-delimited list of parameters to reset. Only runs if
``reset_syslog_config`` is set to ``True``. If ``reset_syslog_config`` is set
to ``True``, but no syslog configs are listed in ``reset_configs``, then
``reset_configs`` will be set to ``all`` by default.
See ``syslog_configs`` parameter above for a list of valid options.
Example:
.. code-block:: yaml
configure-host-syslog:
esxi.syslog_configured:
- syslog_configs:
loghost: ssl://localhost:5432,tcp://10.1.0.1:1514
default-timeout: 120
- firewall: True
- reset_service: True
- reset_syslog_config: True
- reset_configs: loghost,default-timeout | [
"Ensures",
"the",
"specified",
"syslog",
"configuration",
"parameters",
".",
"By",
"default",
"this",
"state",
"will",
"reset",
"the",
"syslog",
"service",
"after",
"any",
"new",
"or",
"changed",
"parameters",
"are",
"set",
"successfully",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L869-L1025 | train |
saltstack/salt | salt/states/esxi.py | diskgroups_configured | def diskgroups_configured(name, diskgroups, erase_disks=False):
'''
Configures the disk groups to use for vsan.
This function will do the following:
1. Check whether or not all disks in the diskgroup spec exist, and raises
and errors if they do not.
2. Create diskgroups with the correct disk configurations if diskgroup
(identified by the cache disk canonical name) doesn't exist
3. Adds extra capacity disks to the existing diskgroup
Example:
.. code:: python
{
'cache_scsi_addr': 'vmhba1:C0:T0:L0',
'capacity_scsi_addrs': [
'vmhba2:C0:T0:L0',
'vmhba3:C0:T0:L0',
'vmhba4:C0:T0:L0',
]
}
name
Mandatory state name
diskgroups
Disk group representation containing scsi disk addresses.
Scsi addresses are expected for disks in the diskgroup:
erase_disks
Specifies whether to erase all partitions on all disks member of the
disk group before the disk group is created. Default value is False.
'''
proxy_details = __salt__['esxi.get_details']()
hostname = proxy_details['host'] if not proxy_details.get('vcenter') \
else proxy_details['esxi_host']
log.info('Running state %s for host \'%s\'', name, hostname)
# Variable used to return the result of the invocation
ret = {'name': name,
'result': None,
'changes': {},
'comments': None}
# Signals if errors have been encountered
errors = False
# Signals if changes are required
changes = False
comments = []
diskgroup_changes = {}
si = None
try:
log.trace('Validating diskgroups_configured input')
schema = DiskGroupsDiskScsiAddressSchema.serialize()
try:
jsonschema.validate({'diskgroups': diskgroups,
'erase_disks': erase_disks}, schema)
except jsonschema.exceptions.ValidationError as exc:
raise InvalidConfigError(exc)
si = __salt__['vsphere.get_service_instance_via_proxy']()
host_disks = __salt__['vsphere.list_disks'](service_instance=si)
if not host_disks:
raise VMwareObjectRetrievalError(
'No disks retrieved from host \'{0}\''.format(hostname))
scsi_addr_to_disk_map = {d['scsi_address']: d for d in host_disks}
log.trace('scsi_addr_to_disk_map = %s', scsi_addr_to_disk_map)
existing_diskgroups = \
__salt__['vsphere.list_diskgroups'](service_instance=si)
cache_disk_to_existing_diskgroup_map = \
{dg['cache_disk']: dg for dg in existing_diskgroups}
except CommandExecutionError as err:
log.error('Error: %s', err)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({
'result': False if not __opts__['test'] else None,
'comment': six.text_type(err)})
return ret
# Iterate through all of the disk groups
for idx, dg in enumerate(diskgroups):
# Check for cache disk
if not dg['cache_scsi_addr'] in scsi_addr_to_disk_map:
comments.append('No cache disk with scsi address \'{0}\' was '
'found.'.format(dg['cache_scsi_addr']))
log.error(comments[-1])
errors = True
continue
# Check for capacity disks
cache_disk_id = scsi_addr_to_disk_map[dg['cache_scsi_addr']]['id']
cache_disk_display = '{0} (id:{1})'.format(dg['cache_scsi_addr'],
cache_disk_id)
bad_scsi_addrs = []
capacity_disk_ids = []
capacity_disk_displays = []
for scsi_addr in dg['capacity_scsi_addrs']:
if scsi_addr not in scsi_addr_to_disk_map:
bad_scsi_addrs.append(scsi_addr)
continue
capacity_disk_ids.append(scsi_addr_to_disk_map[scsi_addr]['id'])
capacity_disk_displays.append(
'{0} (id:{1})'.format(scsi_addr, capacity_disk_ids[-1]))
if bad_scsi_addrs:
comments.append('Error in diskgroup #{0}: capacity disks with '
'scsi addresses {1} were not found.'
''.format(idx,
', '.join(['\'{0}\''.format(a)
for a in bad_scsi_addrs])))
log.error(comments[-1])
errors = True
continue
if not cache_disk_to_existing_diskgroup_map.get(cache_disk_id):
# A new diskgroup needs to be created
log.trace('erase_disks = %s', erase_disks)
if erase_disks:
if __opts__['test']:
comments.append('State {0} will '
'erase all disks of disk group #{1}; '
'cache disk: \'{2}\', '
'capacity disk(s): {3}.'
''.format(name, idx, cache_disk_display,
', '.join(
['\'{}\''.format(a) for a in
capacity_disk_displays])))
else:
# Erase disk group disks
for disk_id in [cache_disk_id] + capacity_disk_ids:
__salt__['vsphere.erase_disk_partitions'](
disk_id=disk_id, service_instance=si)
comments.append('Erased disks of diskgroup #{0}; '
'cache disk: \'{1}\', capacity disk(s): '
'{2}'.format(
idx, cache_disk_display,
', '.join(['\'{0}\''.format(a) for a in
capacity_disk_displays])))
log.info(comments[-1])
if __opts__['test']:
comments.append('State {0} will create '
'the disk group #{1}; cache disk: \'{2}\', '
'capacity disk(s): {3}.'
.format(name, idx, cache_disk_display,
', '.join(['\'{0}\''.format(a) for a in
capacity_disk_displays])))
log.info(comments[-1])
changes = True
continue
try:
__salt__['vsphere.create_diskgroup'](cache_disk_id,
capacity_disk_ids,
safety_checks=False,
service_instance=si)
except VMwareSaltError as err:
comments.append('Error creating disk group #{0}: '
'{1}.'.format(idx, err))
log.error(comments[-1])
errors = True
continue
comments.append('Created disk group #\'{0}\'.'.format(idx))
log.info(comments[-1])
diskgroup_changes[six.text_type(idx)] = \
{'new': {'cache': cache_disk_display,
'capacity': capacity_disk_displays}}
changes = True
continue
# The diskgroup exists; checking the capacity disks
log.debug('Disk group #%s exists. Checking capacity disks: %s.',
idx, capacity_disk_displays)
existing_diskgroup = \
cache_disk_to_existing_diskgroup_map.get(cache_disk_id)
existing_capacity_disk_displays = \
['{0} (id:{1})'.format([d['scsi_address'] for d in host_disks
if d['id'] == disk_id][0], disk_id)
for disk_id in existing_diskgroup['capacity_disks']]
# Populate added disks and removed disks and their displays
added_capacity_disk_ids = []
added_capacity_disk_displays = []
removed_capacity_disk_ids = []
removed_capacity_disk_displays = []
for disk_id in capacity_disk_ids:
if disk_id not in existing_diskgroup['capacity_disks']:
disk_scsi_addr = [d['scsi_address'] for d in host_disks
if d['id'] == disk_id][0]
added_capacity_disk_ids.append(disk_id)
added_capacity_disk_displays.append(
'{0} (id:{1})'.format(disk_scsi_addr, disk_id))
for disk_id in existing_diskgroup['capacity_disks']:
if disk_id not in capacity_disk_ids:
disk_scsi_addr = [d['scsi_address'] for d in host_disks
if d['id'] == disk_id][0]
removed_capacity_disk_ids.append(disk_id)
removed_capacity_disk_displays.append(
'{0} (id:{1})'.format(disk_scsi_addr, disk_id))
log.debug('Disk group #%s: existing capacity disk ids: %s; added '
'capacity disk ids: %s; removed capacity disk ids: %s',
idx, existing_capacity_disk_displays,
added_capacity_disk_displays, removed_capacity_disk_displays)
#TODO revisit this when removing capacity disks is supported
if removed_capacity_disk_ids:
comments.append(
'Error removing capacity disk(s) {0} from disk group #{1}; '
'operation is not supported.'
''.format(', '.join(['\'{0}\''.format(id) for id in
removed_capacity_disk_displays]), idx))
log.error(comments[-1])
errors = True
continue
if added_capacity_disk_ids:
# Capacity disks need to be added to disk group
# Building a string representation of the capacity disks
# that need to be added
s = ', '.join(['\'{0}\''.format(id) for id in
added_capacity_disk_displays])
if __opts__['test']:
comments.append('State {0} will add '
'capacity disk(s) {1} to disk group #{2}.'
''.format(name, s, idx))
log.info(comments[-1])
changes = True
continue
try:
__salt__['vsphere.add_capacity_to_diskgroup'](
cache_disk_id,
added_capacity_disk_ids,
safety_checks=False,
service_instance=si)
except VMwareSaltError as err:
comments.append('Error adding capacity disk(s) {0} to '
'disk group #{1}: {2}.'.format(s, idx, err))
log.error(comments[-1])
errors = True
continue
com = ('Added capacity disk(s) {0} to disk group #{1}'
''.format(s, idx))
log.info(com)
comments.append(com)
diskgroup_changes[six.text_type(idx)] = \
{'new': {'cache': cache_disk_display,
'capacity': capacity_disk_displays},
'old': {'cache': cache_disk_display,
'capacity': existing_capacity_disk_displays}}
changes = True
continue
# No capacity needs to be added
s = ('Disk group #{0} is correctly configured. Nothing to be done.'
''.format(idx))
log.info(s)
comments.append(s)
__salt__['vsphere.disconnect'](si)
#Build the final return message
result = (True if not (changes or errors) else # no changes/errors
None if __opts__['test'] else # running in test mode
False if errors else True) # found errors; defaults to True
ret.update({'result': result,
'comment': '\n'.join(comments),
'changes': diskgroup_changes})
return ret | python | def diskgroups_configured(name, diskgroups, erase_disks=False):
'''
Configures the disk groups to use for vsan.
This function will do the following:
1. Check whether or not all disks in the diskgroup spec exist, and raises
and errors if they do not.
2. Create diskgroups with the correct disk configurations if diskgroup
(identified by the cache disk canonical name) doesn't exist
3. Adds extra capacity disks to the existing diskgroup
Example:
.. code:: python
{
'cache_scsi_addr': 'vmhba1:C0:T0:L0',
'capacity_scsi_addrs': [
'vmhba2:C0:T0:L0',
'vmhba3:C0:T0:L0',
'vmhba4:C0:T0:L0',
]
}
name
Mandatory state name
diskgroups
Disk group representation containing scsi disk addresses.
Scsi addresses are expected for disks in the diskgroup:
erase_disks
Specifies whether to erase all partitions on all disks member of the
disk group before the disk group is created. Default value is False.
'''
proxy_details = __salt__['esxi.get_details']()
hostname = proxy_details['host'] if not proxy_details.get('vcenter') \
else proxy_details['esxi_host']
log.info('Running state %s for host \'%s\'', name, hostname)
# Variable used to return the result of the invocation
ret = {'name': name,
'result': None,
'changes': {},
'comments': None}
# Signals if errors have been encountered
errors = False
# Signals if changes are required
changes = False
comments = []
diskgroup_changes = {}
si = None
try:
log.trace('Validating diskgroups_configured input')
schema = DiskGroupsDiskScsiAddressSchema.serialize()
try:
jsonschema.validate({'diskgroups': diskgroups,
'erase_disks': erase_disks}, schema)
except jsonschema.exceptions.ValidationError as exc:
raise InvalidConfigError(exc)
si = __salt__['vsphere.get_service_instance_via_proxy']()
host_disks = __salt__['vsphere.list_disks'](service_instance=si)
if not host_disks:
raise VMwareObjectRetrievalError(
'No disks retrieved from host \'{0}\''.format(hostname))
scsi_addr_to_disk_map = {d['scsi_address']: d for d in host_disks}
log.trace('scsi_addr_to_disk_map = %s', scsi_addr_to_disk_map)
existing_diskgroups = \
__salt__['vsphere.list_diskgroups'](service_instance=si)
cache_disk_to_existing_diskgroup_map = \
{dg['cache_disk']: dg for dg in existing_diskgroups}
except CommandExecutionError as err:
log.error('Error: %s', err)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({
'result': False if not __opts__['test'] else None,
'comment': six.text_type(err)})
return ret
# Iterate through all of the disk groups
for idx, dg in enumerate(diskgroups):
# Check for cache disk
if not dg['cache_scsi_addr'] in scsi_addr_to_disk_map:
comments.append('No cache disk with scsi address \'{0}\' was '
'found.'.format(dg['cache_scsi_addr']))
log.error(comments[-1])
errors = True
continue
# Check for capacity disks
cache_disk_id = scsi_addr_to_disk_map[dg['cache_scsi_addr']]['id']
cache_disk_display = '{0} (id:{1})'.format(dg['cache_scsi_addr'],
cache_disk_id)
bad_scsi_addrs = []
capacity_disk_ids = []
capacity_disk_displays = []
for scsi_addr in dg['capacity_scsi_addrs']:
if scsi_addr not in scsi_addr_to_disk_map:
bad_scsi_addrs.append(scsi_addr)
continue
capacity_disk_ids.append(scsi_addr_to_disk_map[scsi_addr]['id'])
capacity_disk_displays.append(
'{0} (id:{1})'.format(scsi_addr, capacity_disk_ids[-1]))
if bad_scsi_addrs:
comments.append('Error in diskgroup #{0}: capacity disks with '
'scsi addresses {1} were not found.'
''.format(idx,
', '.join(['\'{0}\''.format(a)
for a in bad_scsi_addrs])))
log.error(comments[-1])
errors = True
continue
if not cache_disk_to_existing_diskgroup_map.get(cache_disk_id):
# A new diskgroup needs to be created
log.trace('erase_disks = %s', erase_disks)
if erase_disks:
if __opts__['test']:
comments.append('State {0} will '
'erase all disks of disk group #{1}; '
'cache disk: \'{2}\', '
'capacity disk(s): {3}.'
''.format(name, idx, cache_disk_display,
', '.join(
['\'{}\''.format(a) for a in
capacity_disk_displays])))
else:
# Erase disk group disks
for disk_id in [cache_disk_id] + capacity_disk_ids:
__salt__['vsphere.erase_disk_partitions'](
disk_id=disk_id, service_instance=si)
comments.append('Erased disks of diskgroup #{0}; '
'cache disk: \'{1}\', capacity disk(s): '
'{2}'.format(
idx, cache_disk_display,
', '.join(['\'{0}\''.format(a) for a in
capacity_disk_displays])))
log.info(comments[-1])
if __opts__['test']:
comments.append('State {0} will create '
'the disk group #{1}; cache disk: \'{2}\', '
'capacity disk(s): {3}.'
.format(name, idx, cache_disk_display,
', '.join(['\'{0}\''.format(a) for a in
capacity_disk_displays])))
log.info(comments[-1])
changes = True
continue
try:
__salt__['vsphere.create_diskgroup'](cache_disk_id,
capacity_disk_ids,
safety_checks=False,
service_instance=si)
except VMwareSaltError as err:
comments.append('Error creating disk group #{0}: '
'{1}.'.format(idx, err))
log.error(comments[-1])
errors = True
continue
comments.append('Created disk group #\'{0}\'.'.format(idx))
log.info(comments[-1])
diskgroup_changes[six.text_type(idx)] = \
{'new': {'cache': cache_disk_display,
'capacity': capacity_disk_displays}}
changes = True
continue
# The diskgroup exists; checking the capacity disks
log.debug('Disk group #%s exists. Checking capacity disks: %s.',
idx, capacity_disk_displays)
existing_diskgroup = \
cache_disk_to_existing_diskgroup_map.get(cache_disk_id)
existing_capacity_disk_displays = \
['{0} (id:{1})'.format([d['scsi_address'] for d in host_disks
if d['id'] == disk_id][0], disk_id)
for disk_id in existing_diskgroup['capacity_disks']]
# Populate added disks and removed disks and their displays
added_capacity_disk_ids = []
added_capacity_disk_displays = []
removed_capacity_disk_ids = []
removed_capacity_disk_displays = []
for disk_id in capacity_disk_ids:
if disk_id not in existing_diskgroup['capacity_disks']:
disk_scsi_addr = [d['scsi_address'] for d in host_disks
if d['id'] == disk_id][0]
added_capacity_disk_ids.append(disk_id)
added_capacity_disk_displays.append(
'{0} (id:{1})'.format(disk_scsi_addr, disk_id))
for disk_id in existing_diskgroup['capacity_disks']:
if disk_id not in capacity_disk_ids:
disk_scsi_addr = [d['scsi_address'] for d in host_disks
if d['id'] == disk_id][0]
removed_capacity_disk_ids.append(disk_id)
removed_capacity_disk_displays.append(
'{0} (id:{1})'.format(disk_scsi_addr, disk_id))
log.debug('Disk group #%s: existing capacity disk ids: %s; added '
'capacity disk ids: %s; removed capacity disk ids: %s',
idx, existing_capacity_disk_displays,
added_capacity_disk_displays, removed_capacity_disk_displays)
#TODO revisit this when removing capacity disks is supported
if removed_capacity_disk_ids:
comments.append(
'Error removing capacity disk(s) {0} from disk group #{1}; '
'operation is not supported.'
''.format(', '.join(['\'{0}\''.format(id) for id in
removed_capacity_disk_displays]), idx))
log.error(comments[-1])
errors = True
continue
if added_capacity_disk_ids:
# Capacity disks need to be added to disk group
# Building a string representation of the capacity disks
# that need to be added
s = ', '.join(['\'{0}\''.format(id) for id in
added_capacity_disk_displays])
if __opts__['test']:
comments.append('State {0} will add '
'capacity disk(s) {1} to disk group #{2}.'
''.format(name, s, idx))
log.info(comments[-1])
changes = True
continue
try:
__salt__['vsphere.add_capacity_to_diskgroup'](
cache_disk_id,
added_capacity_disk_ids,
safety_checks=False,
service_instance=si)
except VMwareSaltError as err:
comments.append('Error adding capacity disk(s) {0} to '
'disk group #{1}: {2}.'.format(s, idx, err))
log.error(comments[-1])
errors = True
continue
com = ('Added capacity disk(s) {0} to disk group #{1}'
''.format(s, idx))
log.info(com)
comments.append(com)
diskgroup_changes[six.text_type(idx)] = \
{'new': {'cache': cache_disk_display,
'capacity': capacity_disk_displays},
'old': {'cache': cache_disk_display,
'capacity': existing_capacity_disk_displays}}
changes = True
continue
# No capacity needs to be added
s = ('Disk group #{0} is correctly configured. Nothing to be done.'
''.format(idx))
log.info(s)
comments.append(s)
__salt__['vsphere.disconnect'](si)
#Build the final return message
result = (True if not (changes or errors) else # no changes/errors
None if __opts__['test'] else # running in test mode
False if errors else True) # found errors; defaults to True
ret.update({'result': result,
'comment': '\n'.join(comments),
'changes': diskgroup_changes})
return ret | [
"def",
"diskgroups_configured",
"(",
"name",
",",
"diskgroups",
",",
"erase_disks",
"=",
"False",
")",
":",
"proxy_details",
"=",
"__salt__",
"[",
"'esxi.get_details'",
"]",
"(",
")",
"hostname",
"=",
"proxy_details",
"[",
"'host'",
"]",
"if",
"not",
"proxy_de... | Configures the disk groups to use for vsan.
This function will do the following:
1. Check whether or not all disks in the diskgroup spec exist, and raises
and errors if they do not.
2. Create diskgroups with the correct disk configurations if diskgroup
(identified by the cache disk canonical name) doesn't exist
3. Adds extra capacity disks to the existing diskgroup
Example:
.. code:: python
{
'cache_scsi_addr': 'vmhba1:C0:T0:L0',
'capacity_scsi_addrs': [
'vmhba2:C0:T0:L0',
'vmhba3:C0:T0:L0',
'vmhba4:C0:T0:L0',
]
}
name
Mandatory state name
diskgroups
Disk group representation containing scsi disk addresses.
Scsi addresses are expected for disks in the diskgroup:
erase_disks
Specifies whether to erase all partitions on all disks member of the
disk group before the disk group is created. Default value is False. | [
"Configures",
"the",
"disk",
"groups",
"to",
"use",
"for",
"vsan",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L1030-L1300 | train |
saltstack/salt | salt/states/esxi.py | host_cache_configured | def host_cache_configured(name, enabled, datastore, swap_size='100%',
dedicated_backing_disk=False,
erase_backing_disk=False):
'''
Configures the host cache used for swapping.
It will do the following:
1. Checks if backing disk exists
2. Creates the VMFS datastore if doesn't exist (datastore partition will be
created and use the entire disk)
3. Raises an error if ``dedicated_backing_disk`` is ``True`` and partitions
already exist on the backing disk
4. Configures host_cache to use a portion of the datastore for caching
(either a specific size or a percentage of the datastore)
Examples
Percentage swap size (can't be 100%)
.. code:: python
{
'enabled': true,
'datastore': {
'backing_disk_scsi_addr': 'vmhba0:C0:T0:L0',
'vmfs_version': 5,
'name': 'hostcache'
}
'dedicated_backing_disk': false
'swap_size': '98%',
}
Fixed sized swap size
.. code:: python
{
'enabled': true,
'datastore': {
'backing_disk_scsi_addr': 'vmhba0:C0:T0:L0',
'vmfs_version': 5,
'name': 'hostcache'
}
'dedicated_backing_disk': true
'swap_size': '10GiB',
}
name
Mandatory state name.
enabled
Specifies whether the host cache is enabled.
datastore
Specifies the host cache datastore.
swap_size
Specifies the size of the host cache swap. Can be a percentage or a
value in GiB. Default value is ``100%``.
dedicated_backing_disk
Specifies whether the backing disk is dedicated to the host cache which
means it must have no other partitions. Default is False
erase_backing_disk
Specifies whether to erase all partitions on the backing disk before
the datastore is created. Default value is False.
'''
log.trace('enabled = %s', enabled)
log.trace('datastore = %s', datastore)
log.trace('swap_size = %s', swap_size)
log.trace('erase_backing_disk = %s', erase_backing_disk)
# Variable used to return the result of the invocation
proxy_details = __salt__['esxi.get_details']()
hostname = proxy_details['host'] if not proxy_details.get('vcenter') \
else proxy_details['esxi_host']
log.trace('hostname = %s', hostname)
log.info('Running host_cache_swap_configured for host \'%s\'', hostname)
ret = {'name': hostname,
'comment': 'Default comments',
'result': None,
'changes': {}}
result = None if __opts__['test'] else True # We assume success
needs_setting = False
comments = []
changes = {}
si = None
try:
log.debug('Validating host_cache_configured input')
schema = HostCacheSchema.serialize()
try:
jsonschema.validate({'enabled': enabled,
'datastore': datastore,
'swap_size': swap_size,
'erase_backing_disk': erase_backing_disk},
schema)
except jsonschema.exceptions.ValidationError as exc:
raise InvalidConfigError(exc)
m = re.match(r'(\d+)(%|GiB)', swap_size)
swap_size_value = int(m.group(1))
swap_type = m.group(2)
log.trace('swap_size_value = %s; swap_type = %s', swap_size_value, swap_type)
si = __salt__['vsphere.get_service_instance_via_proxy']()
host_cache = __salt__['vsphere.get_host_cache'](service_instance=si)
# Check enabled
if host_cache['enabled'] != enabled:
changes.update({'enabled': {'old': host_cache['enabled'],
'new': enabled}})
needs_setting = True
# Check datastores
existing_datastores = None
if host_cache.get('datastore'):
existing_datastores = \
__salt__['vsphere.list_datastores_via_proxy'](
datastore_names=[datastore['name']],
service_instance=si)
# Retrieve backing disks
existing_disks = __salt__['vsphere.list_disks'](
scsi_addresses=[datastore['backing_disk_scsi_addr']],
service_instance=si)
if not existing_disks:
raise VMwareObjectRetrievalError(
'Disk with scsi address \'{0}\' was not found in host \'{1}\''
''.format(datastore['backing_disk_scsi_addr'], hostname))
backing_disk = existing_disks[0]
backing_disk_display = '{0} (id:{1})'.format(
backing_disk['scsi_address'], backing_disk['id'])
log.trace('backing_disk = %s', backing_disk_display)
existing_datastore = None
if not existing_datastores:
# Check if disk needs to be erased
if erase_backing_disk:
if __opts__['test']:
comments.append('State {0} will erase '
'the backing disk \'{1}\' on host \'{2}\'.'
''.format(name, backing_disk_display,
hostname))
log.info(comments[-1])
else:
# Erase disk
__salt__['vsphere.erase_disk_partitions'](
disk_id=backing_disk['id'], service_instance=si)
comments.append('Erased backing disk \'{0}\' on host '
'\'{1}\'.'.format(backing_disk_display,
hostname))
log.info(comments[-1])
# Create the datastore
if __opts__['test']:
comments.append('State {0} will create '
'the datastore \'{1}\', with backing disk '
'\'{2}\', on host \'{3}\'.'
''.format(name, datastore['name'],
backing_disk_display, hostname))
log.info(comments[-1])
else:
if dedicated_backing_disk:
# Check backing disk doesn't already have partitions
partitions = __salt__['vsphere.list_disk_partitions'](
disk_id=backing_disk['id'], service_instance=si)
log.trace('partitions = %s', partitions)
# We will ignore the mbr partitions
non_mbr_partitions = [p for p in partitions
if p['format'] != 'mbr']
if non_mbr_partitions:
raise VMwareApiError(
'Backing disk \'{0}\' has unexpected partitions'
''.format(backing_disk_display))
__salt__['vsphere.create_vmfs_datastore'](
datastore['name'], existing_disks[0]['id'],
datastore['vmfs_version'], service_instance=si)
comments.append('Created vmfs datastore \'{0}\', backed by '
'disk \'{1}\', on host \'{2}\'.'
''.format(datastore['name'],
backing_disk_display, hostname))
log.info(comments[-1])
changes.update(
{'datastore':
{'new': {'name': datastore['name'],
'backing_disk': backing_disk_display}}})
existing_datastore = \
__salt__['vsphere.list_datastores_via_proxy'](
datastore_names=[datastore['name']],
service_instance=si)[0]
needs_setting = True
else:
# Check datastore is backed by the correct disk
if not existing_datastores[0].get('backing_disk_ids'):
raise VMwareSaltError('Datastore \'{0}\' doesn\'t have a '
'backing disk'
''.format(datastore['name']))
if backing_disk['id'] not in \
existing_datastores[0]['backing_disk_ids']:
raise VMwareSaltError(
'Datastore \'{0}\' is not backed by the correct disk: '
'expected \'{1}\'; got {2}'
''.format(
datastore['name'], backing_disk['id'],
', '.join(
['\'{0}\''.format(disk) for disk in
existing_datastores[0]['backing_disk_ids']])))
comments.append('Datastore \'{0}\' already exists on host \'{1}\' '
'and is backed by disk \'{2}\'. Nothing to be '
'done.'.format(datastore['name'], hostname,
backing_disk_display))
existing_datastore = existing_datastores[0]
log.trace('existing_datastore = %s', existing_datastore)
log.info(comments[-1])
if existing_datastore:
# The following comparisons can be done if the existing_datastore
# is set; it may not be set if running in test mode
#
# We support percent, as well as MiB, we will convert the size
# to MiB, multiples of 1024 (VMware SDK limitation)
if swap_type == '%':
# Percentage swap size
# Convert from bytes to MiB
raw_size_MiB = (swap_size_value/100.0) * \
(existing_datastore['capacity']/1024/1024)
else:
raw_size_MiB = swap_size_value * 1024
log.trace('raw_size = %sMiB', raw_size_MiB)
swap_size_MiB = int(raw_size_MiB/1024)*1024
log.trace('adjusted swap_size = %sMiB', swap_size_MiB)
existing_swap_size_MiB = 0
m = re.match(r'(\d+)MiB', host_cache.get('swap_size')) if \
host_cache.get('swap_size') else None
if m:
# if swap_size from the host is set and has an expected value
# we are going to parse it to get the number of MiBs
existing_swap_size_MiB = int(m.group(1))
if not existing_swap_size_MiB == swap_size_MiB:
needs_setting = True
changes.update(
{'swap_size':
{'old': '{}GiB'.format(existing_swap_size_MiB/1024),
'new': '{}GiB'.format(swap_size_MiB/1024)}})
if needs_setting:
if __opts__['test']:
comments.append('State {0} will configure '
'the host cache on host \'{1}\' to: {2}.'
''.format(name, hostname,
{'enabled': enabled,
'datastore_name': datastore['name'],
'swap_size': swap_size}))
else:
if (existing_datastore['capacity'] / 1024.0**2) < \
swap_size_MiB:
raise ArgumentValueError(
'Capacity of host cache datastore \'{0}\' ({1} MiB) is '
'smaller than the required swap size ({2} MiB)'
''.format(existing_datastore['name'],
existing_datastore['capacity'] / 1024.0**2,
swap_size_MiB))
__salt__['vsphere.configure_host_cache'](
enabled,
datastore['name'],
swap_size_MiB=swap_size_MiB,
service_instance=si)
comments.append('Host cache configured on host '
'\'{0}\'.'.format(hostname))
else:
comments.append('Host cache on host \'{0}\' is already correctly '
'configured. Nothing to be done.'.format(hostname))
result = True
__salt__['vsphere.disconnect'](si)
log.info(comments[-1])
ret.update({'comment': '\n'.join(comments),
'result': result,
'changes': changes})
return ret
except CommandExecutionError as err:
log.error('Error: %s.', err)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({
'result': False if not __opts__['test'] else None,
'comment': '{}.'.format(err)})
return ret | python | def host_cache_configured(name, enabled, datastore, swap_size='100%',
dedicated_backing_disk=False,
erase_backing_disk=False):
'''
Configures the host cache used for swapping.
It will do the following:
1. Checks if backing disk exists
2. Creates the VMFS datastore if doesn't exist (datastore partition will be
created and use the entire disk)
3. Raises an error if ``dedicated_backing_disk`` is ``True`` and partitions
already exist on the backing disk
4. Configures host_cache to use a portion of the datastore for caching
(either a specific size or a percentage of the datastore)
Examples
Percentage swap size (can't be 100%)
.. code:: python
{
'enabled': true,
'datastore': {
'backing_disk_scsi_addr': 'vmhba0:C0:T0:L0',
'vmfs_version': 5,
'name': 'hostcache'
}
'dedicated_backing_disk': false
'swap_size': '98%',
}
Fixed sized swap size
.. code:: python
{
'enabled': true,
'datastore': {
'backing_disk_scsi_addr': 'vmhba0:C0:T0:L0',
'vmfs_version': 5,
'name': 'hostcache'
}
'dedicated_backing_disk': true
'swap_size': '10GiB',
}
name
Mandatory state name.
enabled
Specifies whether the host cache is enabled.
datastore
Specifies the host cache datastore.
swap_size
Specifies the size of the host cache swap. Can be a percentage or a
value in GiB. Default value is ``100%``.
dedicated_backing_disk
Specifies whether the backing disk is dedicated to the host cache which
means it must have no other partitions. Default is False
erase_backing_disk
Specifies whether to erase all partitions on the backing disk before
the datastore is created. Default value is False.
'''
log.trace('enabled = %s', enabled)
log.trace('datastore = %s', datastore)
log.trace('swap_size = %s', swap_size)
log.trace('erase_backing_disk = %s', erase_backing_disk)
# Variable used to return the result of the invocation
proxy_details = __salt__['esxi.get_details']()
hostname = proxy_details['host'] if not proxy_details.get('vcenter') \
else proxy_details['esxi_host']
log.trace('hostname = %s', hostname)
log.info('Running host_cache_swap_configured for host \'%s\'', hostname)
ret = {'name': hostname,
'comment': 'Default comments',
'result': None,
'changes': {}}
result = None if __opts__['test'] else True # We assume success
needs_setting = False
comments = []
changes = {}
si = None
try:
log.debug('Validating host_cache_configured input')
schema = HostCacheSchema.serialize()
try:
jsonschema.validate({'enabled': enabled,
'datastore': datastore,
'swap_size': swap_size,
'erase_backing_disk': erase_backing_disk},
schema)
except jsonschema.exceptions.ValidationError as exc:
raise InvalidConfigError(exc)
m = re.match(r'(\d+)(%|GiB)', swap_size)
swap_size_value = int(m.group(1))
swap_type = m.group(2)
log.trace('swap_size_value = %s; swap_type = %s', swap_size_value, swap_type)
si = __salt__['vsphere.get_service_instance_via_proxy']()
host_cache = __salt__['vsphere.get_host_cache'](service_instance=si)
# Check enabled
if host_cache['enabled'] != enabled:
changes.update({'enabled': {'old': host_cache['enabled'],
'new': enabled}})
needs_setting = True
# Check datastores
existing_datastores = None
if host_cache.get('datastore'):
existing_datastores = \
__salt__['vsphere.list_datastores_via_proxy'](
datastore_names=[datastore['name']],
service_instance=si)
# Retrieve backing disks
existing_disks = __salt__['vsphere.list_disks'](
scsi_addresses=[datastore['backing_disk_scsi_addr']],
service_instance=si)
if not existing_disks:
raise VMwareObjectRetrievalError(
'Disk with scsi address \'{0}\' was not found in host \'{1}\''
''.format(datastore['backing_disk_scsi_addr'], hostname))
backing_disk = existing_disks[0]
backing_disk_display = '{0} (id:{1})'.format(
backing_disk['scsi_address'], backing_disk['id'])
log.trace('backing_disk = %s', backing_disk_display)
existing_datastore = None
if not existing_datastores:
# Check if disk needs to be erased
if erase_backing_disk:
if __opts__['test']:
comments.append('State {0} will erase '
'the backing disk \'{1}\' on host \'{2}\'.'
''.format(name, backing_disk_display,
hostname))
log.info(comments[-1])
else:
# Erase disk
__salt__['vsphere.erase_disk_partitions'](
disk_id=backing_disk['id'], service_instance=si)
comments.append('Erased backing disk \'{0}\' on host '
'\'{1}\'.'.format(backing_disk_display,
hostname))
log.info(comments[-1])
# Create the datastore
if __opts__['test']:
comments.append('State {0} will create '
'the datastore \'{1}\', with backing disk '
'\'{2}\', on host \'{3}\'.'
''.format(name, datastore['name'],
backing_disk_display, hostname))
log.info(comments[-1])
else:
if dedicated_backing_disk:
# Check backing disk doesn't already have partitions
partitions = __salt__['vsphere.list_disk_partitions'](
disk_id=backing_disk['id'], service_instance=si)
log.trace('partitions = %s', partitions)
# We will ignore the mbr partitions
non_mbr_partitions = [p for p in partitions
if p['format'] != 'mbr']
if non_mbr_partitions:
raise VMwareApiError(
'Backing disk \'{0}\' has unexpected partitions'
''.format(backing_disk_display))
__salt__['vsphere.create_vmfs_datastore'](
datastore['name'], existing_disks[0]['id'],
datastore['vmfs_version'], service_instance=si)
comments.append('Created vmfs datastore \'{0}\', backed by '
'disk \'{1}\', on host \'{2}\'.'
''.format(datastore['name'],
backing_disk_display, hostname))
log.info(comments[-1])
changes.update(
{'datastore':
{'new': {'name': datastore['name'],
'backing_disk': backing_disk_display}}})
existing_datastore = \
__salt__['vsphere.list_datastores_via_proxy'](
datastore_names=[datastore['name']],
service_instance=si)[0]
needs_setting = True
else:
# Check datastore is backed by the correct disk
if not existing_datastores[0].get('backing_disk_ids'):
raise VMwareSaltError('Datastore \'{0}\' doesn\'t have a '
'backing disk'
''.format(datastore['name']))
if backing_disk['id'] not in \
existing_datastores[0]['backing_disk_ids']:
raise VMwareSaltError(
'Datastore \'{0}\' is not backed by the correct disk: '
'expected \'{1}\'; got {2}'
''.format(
datastore['name'], backing_disk['id'],
', '.join(
['\'{0}\''.format(disk) for disk in
existing_datastores[0]['backing_disk_ids']])))
comments.append('Datastore \'{0}\' already exists on host \'{1}\' '
'and is backed by disk \'{2}\'. Nothing to be '
'done.'.format(datastore['name'], hostname,
backing_disk_display))
existing_datastore = existing_datastores[0]
log.trace('existing_datastore = %s', existing_datastore)
log.info(comments[-1])
if existing_datastore:
# The following comparisons can be done if the existing_datastore
# is set; it may not be set if running in test mode
#
# We support percent, as well as MiB, we will convert the size
# to MiB, multiples of 1024 (VMware SDK limitation)
if swap_type == '%':
# Percentage swap size
# Convert from bytes to MiB
raw_size_MiB = (swap_size_value/100.0) * \
(existing_datastore['capacity']/1024/1024)
else:
raw_size_MiB = swap_size_value * 1024
log.trace('raw_size = %sMiB', raw_size_MiB)
swap_size_MiB = int(raw_size_MiB/1024)*1024
log.trace('adjusted swap_size = %sMiB', swap_size_MiB)
existing_swap_size_MiB = 0
m = re.match(r'(\d+)MiB', host_cache.get('swap_size')) if \
host_cache.get('swap_size') else None
if m:
# if swap_size from the host is set and has an expected value
# we are going to parse it to get the number of MiBs
existing_swap_size_MiB = int(m.group(1))
if not existing_swap_size_MiB == swap_size_MiB:
needs_setting = True
changes.update(
{'swap_size':
{'old': '{}GiB'.format(existing_swap_size_MiB/1024),
'new': '{}GiB'.format(swap_size_MiB/1024)}})
if needs_setting:
if __opts__['test']:
comments.append('State {0} will configure '
'the host cache on host \'{1}\' to: {2}.'
''.format(name, hostname,
{'enabled': enabled,
'datastore_name': datastore['name'],
'swap_size': swap_size}))
else:
if (existing_datastore['capacity'] / 1024.0**2) < \
swap_size_MiB:
raise ArgumentValueError(
'Capacity of host cache datastore \'{0}\' ({1} MiB) is '
'smaller than the required swap size ({2} MiB)'
''.format(existing_datastore['name'],
existing_datastore['capacity'] / 1024.0**2,
swap_size_MiB))
__salt__['vsphere.configure_host_cache'](
enabled,
datastore['name'],
swap_size_MiB=swap_size_MiB,
service_instance=si)
comments.append('Host cache configured on host '
'\'{0}\'.'.format(hostname))
else:
comments.append('Host cache on host \'{0}\' is already correctly '
'configured. Nothing to be done.'.format(hostname))
result = True
__salt__['vsphere.disconnect'](si)
log.info(comments[-1])
ret.update({'comment': '\n'.join(comments),
'result': result,
'changes': changes})
return ret
except CommandExecutionError as err:
log.error('Error: %s.', err)
if si:
__salt__['vsphere.disconnect'](si)
ret.update({
'result': False if not __opts__['test'] else None,
'comment': '{}.'.format(err)})
return ret | [
"def",
"host_cache_configured",
"(",
"name",
",",
"enabled",
",",
"datastore",
",",
"swap_size",
"=",
"'100%'",
",",
"dedicated_backing_disk",
"=",
"False",
",",
"erase_backing_disk",
"=",
"False",
")",
":",
"log",
".",
"trace",
"(",
"'enabled = %s'",
",",
"en... | Configures the host cache used for swapping.
It will do the following:
1. Checks if backing disk exists
2. Creates the VMFS datastore if doesn't exist (datastore partition will be
created and use the entire disk)
3. Raises an error if ``dedicated_backing_disk`` is ``True`` and partitions
already exist on the backing disk
4. Configures host_cache to use a portion of the datastore for caching
(either a specific size or a percentage of the datastore)
Examples
Percentage swap size (can't be 100%)
.. code:: python
{
'enabled': true,
'datastore': {
'backing_disk_scsi_addr': 'vmhba0:C0:T0:L0',
'vmfs_version': 5,
'name': 'hostcache'
}
'dedicated_backing_disk': false
'swap_size': '98%',
}
Fixed sized swap size
.. code:: python
{
'enabled': true,
'datastore': {
'backing_disk_scsi_addr': 'vmhba0:C0:T0:L0',
'vmfs_version': 5,
'name': 'hostcache'
}
'dedicated_backing_disk': true
'swap_size': '10GiB',
}
name
Mandatory state name.
enabled
Specifies whether the host cache is enabled.
datastore
Specifies the host cache datastore.
swap_size
Specifies the size of the host cache swap. Can be a percentage or a
value in GiB. Default value is ``100%``.
dedicated_backing_disk
Specifies whether the backing disk is dedicated to the host cache which
means it must have no other partitions. Default is False
erase_backing_disk
Specifies whether to erase all partitions on the backing disk before
the datastore is created. Default value is False. | [
"Configures",
"the",
"host",
"cache",
"used",
"for",
"swapping",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L1305-L1594 | train |
saltstack/salt | salt/states/cimc.py | hostname | def hostname(name, hostname=None):
'''
Ensures that the hostname is set to the specified value.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
hostname(str): The hostname of the server.
SLS Example:
.. code-block:: yaml
set_name:
cimc.hostname:
- hostname: foobar
'''
ret = _default_ret(name)
current_name = __salt__['cimc.get_hostname']()
req_change = False
try:
if current_name != hostname:
req_change = True
if req_change:
update = __salt__['cimc.set_hostname'](hostname)
if not update:
ret['result'] = False
ret['comment'] = "Error setting hostname."
return ret
ret['changes']['before'] = current_name
ret['changes']['after'] = hostname
ret['comment'] = "Hostname modified."
else:
ret['comment'] = "Hostname already configured. No changes required."
except Exception as err:
ret['result'] = False
ret['comment'] = "Error occurred setting hostname."
log.error(err)
return ret
ret['result'] = True
return ret | python | def hostname(name, hostname=None):
'''
Ensures that the hostname is set to the specified value.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
hostname(str): The hostname of the server.
SLS Example:
.. code-block:: yaml
set_name:
cimc.hostname:
- hostname: foobar
'''
ret = _default_ret(name)
current_name = __salt__['cimc.get_hostname']()
req_change = False
try:
if current_name != hostname:
req_change = True
if req_change:
update = __salt__['cimc.set_hostname'](hostname)
if not update:
ret['result'] = False
ret['comment'] = "Error setting hostname."
return ret
ret['changes']['before'] = current_name
ret['changes']['after'] = hostname
ret['comment'] = "Hostname modified."
else:
ret['comment'] = "Hostname already configured. No changes required."
except Exception as err:
ret['result'] = False
ret['comment'] = "Error occurred setting hostname."
log.error(err)
return ret
ret['result'] = True
return ret | [
"def",
"hostname",
"(",
"name",
",",
"hostname",
"=",
"None",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"current_name",
"=",
"__salt__",
"[",
"'cimc.get_hostname'",
"]",
"(",
")",
"req_change",
"=",
"False",
"try",
":",
"if",
"current_name",
... | Ensures that the hostname is set to the specified value.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
hostname(str): The hostname of the server.
SLS Example:
.. code-block:: yaml
set_name:
cimc.hostname:
- hostname: foobar | [
"Ensures",
"that",
"the",
"hostname",
"is",
"set",
"to",
"the",
"specified",
"value",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cimc.py#L46-L100 | train |
saltstack/salt | salt/states/cimc.py | logging_levels | def logging_levels(name, remote=None, local=None):
'''
Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
SLS Example:
.. code-block:: yaml
logging_levels:
cimc.logging_levels:
- remote: informational
- local: notice
'''
ret = _default_ret(name)
syslog_conf = __salt__['cimc.get_syslog_settings']()
req_change = False
try:
syslog_dict = syslog_conf['outConfigs']['commSyslog'][0]
if remote and syslog_dict['remoteSeverity'] != remote:
req_change = True
elif local and syslog_dict['localSeverity'] != local:
req_change = True
if req_change:
update = __salt__['cimc.set_logging_levels'](remote, local)
if update['outConfig']['commSyslog'][0]['status'] != 'modified':
ret['result'] = False
ret['comment'] = "Error setting logging levels."
return ret
ret['changes']['before'] = syslog_conf
ret['changes']['after'] = __salt__['cimc.get_syslog_settings']()
ret['comment'] = "Logging level settings modified."
else:
ret['comment'] = "Logging level already configured. No changes required."
except Exception as err:
ret['result'] = False
ret['comment'] = "Error occurred setting logging level settings."
log.error(err)
return ret
ret['result'] = True
return ret | python | def logging_levels(name, remote=None, local=None):
'''
Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
SLS Example:
.. code-block:: yaml
logging_levels:
cimc.logging_levels:
- remote: informational
- local: notice
'''
ret = _default_ret(name)
syslog_conf = __salt__['cimc.get_syslog_settings']()
req_change = False
try:
syslog_dict = syslog_conf['outConfigs']['commSyslog'][0]
if remote and syslog_dict['remoteSeverity'] != remote:
req_change = True
elif local and syslog_dict['localSeverity'] != local:
req_change = True
if req_change:
update = __salt__['cimc.set_logging_levels'](remote, local)
if update['outConfig']['commSyslog'][0]['status'] != 'modified':
ret['result'] = False
ret['comment'] = "Error setting logging levels."
return ret
ret['changes']['before'] = syslog_conf
ret['changes']['after'] = __salt__['cimc.get_syslog_settings']()
ret['comment'] = "Logging level settings modified."
else:
ret['comment'] = "Logging level already configured. No changes required."
except Exception as err:
ret['result'] = False
ret['comment'] = "Error occurred setting logging level settings."
log.error(err)
return ret
ret['result'] = True
return ret | [
"def",
"logging_levels",
"(",
"name",
",",
"remote",
"=",
"None",
",",
"local",
"=",
"None",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"syslog_conf",
"=",
"__salt__",
"[",
"'cimc.get_syslog_settings'",
"]",
"(",
")",
"req_change",
"=",
"False... | Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
remote(str): The logging level for SYSLOG logs.
local(str): The logging level for the local device.
SLS Example:
.. code-block:: yaml
logging_levels:
cimc.logging_levels:
- remote: informational
- local: notice | [
"Ensures",
"that",
"the",
"logging",
"levels",
"are",
"set",
"on",
"the",
"device",
".",
"The",
"logging",
"levels",
"must",
"match",
"the",
"following",
"options",
":",
"emergency",
"alert",
"critical",
"error",
"warning",
"notice",
"informational",
"debug",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cimc.py#L103-L165 | train |
saltstack/salt | salt/states/cimc.py | ntp | def ntp(name, servers):
'''
Ensures that the NTP servers are configured. Servers are provided as an individual string or list format. Only four
NTP servers will be reviewed. Any entries past four will be ignored.
name: The name of the module function to execute.
servers(str, list): The IP address or FQDN of the NTP servers.
SLS Example:
.. code-block:: yaml
ntp_configuration_list:
cimc.ntp:
- servers:
- foo.bar.com
- 10.10.10.10
ntp_configuration_str:
cimc.ntp:
- servers: foo.bar.com
'''
ret = _default_ret(name)
ntp_servers = ['', '', '', '']
# Parse our server arguments
if isinstance(servers, list):
i = 0
for x in servers:
ntp_servers[i] = x
i += 1
else:
ntp_servers[0] = servers
conf = __salt__['cimc.get_ntp']()
# Check if our NTP configuration is already set
req_change = False
try:
if conf['outConfigs']['commNtpProvider'][0]['ntpEnable'] != 'yes' \
or ntp_servers[0] != conf['outConfigs']['commNtpProvider'][0]['ntpServer1'] \
or ntp_servers[1] != conf['outConfigs']['commNtpProvider'][0]['ntpServer2'] \
or ntp_servers[2] != conf['outConfigs']['commNtpProvider'][0]['ntpServer3'] \
or ntp_servers[3] != conf['outConfigs']['commNtpProvider'][0]['ntpServer4']:
req_change = True
except KeyError as err:
ret['result'] = False
ret['comment'] = "Unable to confirm current NTP settings."
log.error(err)
return ret
if req_change:
try:
update = __salt__['cimc.set_ntp_server'](ntp_servers[0],
ntp_servers[1],
ntp_servers[2],
ntp_servers[3])
if update['outConfig']['commNtpProvider'][0]['status'] != 'modified':
ret['result'] = False
ret['comment'] = "Error setting NTP configuration."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting NTP configuration."
log.error(err)
return ret
ret['changes']['before'] = conf
ret['changes']['after'] = __salt__['cimc.get_ntp']()
ret['comment'] = "NTP settings modified."
else:
ret['comment'] = "NTP already configured. No changes required."
ret['result'] = True
return ret | python | def ntp(name, servers):
'''
Ensures that the NTP servers are configured. Servers are provided as an individual string or list format. Only four
NTP servers will be reviewed. Any entries past four will be ignored.
name: The name of the module function to execute.
servers(str, list): The IP address or FQDN of the NTP servers.
SLS Example:
.. code-block:: yaml
ntp_configuration_list:
cimc.ntp:
- servers:
- foo.bar.com
- 10.10.10.10
ntp_configuration_str:
cimc.ntp:
- servers: foo.bar.com
'''
ret = _default_ret(name)
ntp_servers = ['', '', '', '']
# Parse our server arguments
if isinstance(servers, list):
i = 0
for x in servers:
ntp_servers[i] = x
i += 1
else:
ntp_servers[0] = servers
conf = __salt__['cimc.get_ntp']()
# Check if our NTP configuration is already set
req_change = False
try:
if conf['outConfigs']['commNtpProvider'][0]['ntpEnable'] != 'yes' \
or ntp_servers[0] != conf['outConfigs']['commNtpProvider'][0]['ntpServer1'] \
or ntp_servers[1] != conf['outConfigs']['commNtpProvider'][0]['ntpServer2'] \
or ntp_servers[2] != conf['outConfigs']['commNtpProvider'][0]['ntpServer3'] \
or ntp_servers[3] != conf['outConfigs']['commNtpProvider'][0]['ntpServer4']:
req_change = True
except KeyError as err:
ret['result'] = False
ret['comment'] = "Unable to confirm current NTP settings."
log.error(err)
return ret
if req_change:
try:
update = __salt__['cimc.set_ntp_server'](ntp_servers[0],
ntp_servers[1],
ntp_servers[2],
ntp_servers[3])
if update['outConfig']['commNtpProvider'][0]['status'] != 'modified':
ret['result'] = False
ret['comment'] = "Error setting NTP configuration."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting NTP configuration."
log.error(err)
return ret
ret['changes']['before'] = conf
ret['changes']['after'] = __salt__['cimc.get_ntp']()
ret['comment'] = "NTP settings modified."
else:
ret['comment'] = "NTP already configured. No changes required."
ret['result'] = True
return ret | [
"def",
"ntp",
"(",
"name",
",",
"servers",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"ntp_servers",
"=",
"[",
"''",
",",
"''",
",",
"''",
",",
"''",
"]",
"# Parse our server arguments",
"if",
"isinstance",
"(",
"servers",
",",
"list",
")"... | Ensures that the NTP servers are configured. Servers are provided as an individual string or list format. Only four
NTP servers will be reviewed. Any entries past four will be ignored.
name: The name of the module function to execute.
servers(str, list): The IP address or FQDN of the NTP servers.
SLS Example:
.. code-block:: yaml
ntp_configuration_list:
cimc.ntp:
- servers:
- foo.bar.com
- 10.10.10.10
ntp_configuration_str:
cimc.ntp:
- servers: foo.bar.com | [
"Ensures",
"that",
"the",
"NTP",
"servers",
"are",
"configured",
".",
"Servers",
"are",
"provided",
"as",
"an",
"individual",
"string",
"or",
"list",
"format",
".",
"Only",
"four",
"NTP",
"servers",
"will",
"be",
"reviewed",
".",
"Any",
"entries",
"past",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cimc.py#L168-L247 | train |
saltstack/salt | salt/states/cimc.py | power_configuration | def power_configuration(name, policy=None, delayType=None, delayValue=None):
'''
Ensures that the power configuration is configured on the system. This is
only available on some C-Series servers.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
SLS Example:
.. code-block:: yaml
reset_power:
cimc.power_configuration:
- policy: reset
- delayType: fixed
- delayValue: 0
power_off:
cimc.power_configuration:
- policy: stay-off
'''
ret = _default_ret(name)
power_conf = __salt__['cimc.get_power_configuration']()
req_change = False
try:
power_dict = power_conf['outConfigs']['biosVfResumeOnACPowerLoss'][0]
if policy and power_dict['vpResumeOnACPowerLoss'] != policy:
req_change = True
elif policy == "reset":
if power_dict['delayType'] != delayType:
req_change = True
elif power_dict['delayType'] == "fixed":
if str(power_dict['delay']) != str(delayValue):
req_change = True
else:
ret['result'] = False
ret['comment'] = "The power policy must be specified."
return ret
if req_change:
update = __salt__['cimc.set_power_configuration'](policy,
delayType,
delayValue)
if update['outConfig']['biosVfResumeOnACPowerLoss'][0]['status'] != 'modified':
ret['result'] = False
ret['comment'] = "Error setting power configuration."
return ret
ret['changes']['before'] = power_conf
ret['changes']['after'] = __salt__['cimc.get_power_configuration']()
ret['comment'] = "Power settings modified."
else:
ret['comment'] = "Power settings already configured. No changes required."
except Exception as err:
ret['result'] = False
ret['comment'] = "Error occurred setting power settings."
log.error(err)
return ret
ret['result'] = True
return ret | python | def power_configuration(name, policy=None, delayType=None, delayValue=None):
'''
Ensures that the power configuration is configured on the system. This is
only available on some C-Series servers.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
SLS Example:
.. code-block:: yaml
reset_power:
cimc.power_configuration:
- policy: reset
- delayType: fixed
- delayValue: 0
power_off:
cimc.power_configuration:
- policy: stay-off
'''
ret = _default_ret(name)
power_conf = __salt__['cimc.get_power_configuration']()
req_change = False
try:
power_dict = power_conf['outConfigs']['biosVfResumeOnACPowerLoss'][0]
if policy and power_dict['vpResumeOnACPowerLoss'] != policy:
req_change = True
elif policy == "reset":
if power_dict['delayType'] != delayType:
req_change = True
elif power_dict['delayType'] == "fixed":
if str(power_dict['delay']) != str(delayValue):
req_change = True
else:
ret['result'] = False
ret['comment'] = "The power policy must be specified."
return ret
if req_change:
update = __salt__['cimc.set_power_configuration'](policy,
delayType,
delayValue)
if update['outConfig']['biosVfResumeOnACPowerLoss'][0]['status'] != 'modified':
ret['result'] = False
ret['comment'] = "Error setting power configuration."
return ret
ret['changes']['before'] = power_conf
ret['changes']['after'] = __salt__['cimc.get_power_configuration']()
ret['comment'] = "Power settings modified."
else:
ret['comment'] = "Power settings already configured. No changes required."
except Exception as err:
ret['result'] = False
ret['comment'] = "Error occurred setting power settings."
log.error(err)
return ret
ret['result'] = True
return ret | [
"def",
"power_configuration",
"(",
"name",
",",
"policy",
"=",
"None",
",",
"delayType",
"=",
"None",
",",
"delayValue",
"=",
"None",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"power_conf",
"=",
"__salt__",
"[",
"'cimc.get_power_configuration'",
... | Ensures that the power configuration is configured on the system. This is
only available on some C-Series servers.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
policy(str): The action to be taken when chassis power is restored after
an unexpected power loss. This can be one of the following:
reset: The server is allowed to boot up normally when power is
restored. The server can restart immediately or, optionally, after a
fixed or random delay.
stay-off: The server remains off until it is manually restarted.
last-state: The server restarts and the system attempts to restore
any processes that were running before power was lost.
delayType(str): If the selected policy is reset, the restart can be
delayed with this option. This can be one of the following:
fixed: The server restarts after a fixed delay.
random: The server restarts after a random delay.
delayValue(int): If a fixed delay is selected, once chassis power is
restored and the Cisco IMC has finished rebooting, the system waits for
the specified number of seconds before restarting the server. Enter an
integer between 0 and 240.
SLS Example:
.. code-block:: yaml
reset_power:
cimc.power_configuration:
- policy: reset
- delayType: fixed
- delayValue: 0
power_off:
cimc.power_configuration:
- policy: stay-off | [
"Ensures",
"that",
"the",
"power",
"configuration",
"is",
"configured",
"on",
"the",
"system",
".",
"This",
"is",
"only",
"available",
"on",
"some",
"C",
"-",
"Series",
"servers",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cimc.py#L250-L348 | train |
saltstack/salt | salt/states/cimc.py | syslog | def syslog(name, primary=None, secondary=None):
'''
Ensures that the syslog servers are set to the specified values. A value of None will be ignored.
name: The name of the module function to execute.
primary(str): The IP address or FQDN of the primary syslog server.
secondary(str): The IP address or FQDN of the secondary syslog server.
SLS Example:
.. code-block:: yaml
syslog_configuration:
cimc.syslog:
- primary: 10.10.10.10
- secondary: foo.bar.com
'''
ret = _default_ret(name)
conf = __salt__['cimc.get_syslog']()
req_change = False
if primary:
prim_change = True
if 'outConfigs' in conf and 'commSyslogClient' in conf['outConfigs']:
for entry in conf['outConfigs']['commSyslogClient']:
if entry['name'] != 'primary':
continue
if entry['adminState'] == 'enabled' and entry['hostname'] == primary:
prim_change = False
if prim_change:
try:
update = __salt__['cimc.set_syslog_server'](primary, "primary")
if update['outConfig']['commSyslogClient'][0]['status'] == 'modified':
req_change = True
else:
ret['result'] = False
ret['comment'] = "Error setting primary SYSLOG server."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting primary SYSLOG server."
log.error(err)
return ret
if secondary:
sec_change = True
if 'outConfig' in conf and 'commSyslogClient' in conf['outConfig']:
for entry in conf['outConfig']['commSyslogClient']:
if entry['name'] != 'secondary':
continue
if entry['adminState'] == 'enabled' and entry['hostname'] == secondary:
sec_change = False
if sec_change:
try:
update = __salt__['cimc.set_syslog_server'](secondary, "secondary")
if update['outConfig']['commSyslogClient'][0]['status'] == 'modified':
req_change = True
else:
ret['result'] = False
ret['comment'] = "Error setting secondary SYSLOG server."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting secondary SYSLOG server."
log.error(err)
return ret
if req_change:
ret['changes']['before'] = conf
ret['changes']['after'] = __salt__['cimc.get_syslog']()
ret['comment'] = "SYSLOG settings modified."
else:
ret['comment'] = "SYSLOG already configured. No changes required."
ret['result'] = True
return ret | python | def syslog(name, primary=None, secondary=None):
'''
Ensures that the syslog servers are set to the specified values. A value of None will be ignored.
name: The name of the module function to execute.
primary(str): The IP address or FQDN of the primary syslog server.
secondary(str): The IP address or FQDN of the secondary syslog server.
SLS Example:
.. code-block:: yaml
syslog_configuration:
cimc.syslog:
- primary: 10.10.10.10
- secondary: foo.bar.com
'''
ret = _default_ret(name)
conf = __salt__['cimc.get_syslog']()
req_change = False
if primary:
prim_change = True
if 'outConfigs' in conf and 'commSyslogClient' in conf['outConfigs']:
for entry in conf['outConfigs']['commSyslogClient']:
if entry['name'] != 'primary':
continue
if entry['adminState'] == 'enabled' and entry['hostname'] == primary:
prim_change = False
if prim_change:
try:
update = __salt__['cimc.set_syslog_server'](primary, "primary")
if update['outConfig']['commSyslogClient'][0]['status'] == 'modified':
req_change = True
else:
ret['result'] = False
ret['comment'] = "Error setting primary SYSLOG server."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting primary SYSLOG server."
log.error(err)
return ret
if secondary:
sec_change = True
if 'outConfig' in conf and 'commSyslogClient' in conf['outConfig']:
for entry in conf['outConfig']['commSyslogClient']:
if entry['name'] != 'secondary':
continue
if entry['adminState'] == 'enabled' and entry['hostname'] == secondary:
sec_change = False
if sec_change:
try:
update = __salt__['cimc.set_syslog_server'](secondary, "secondary")
if update['outConfig']['commSyslogClient'][0]['status'] == 'modified':
req_change = True
else:
ret['result'] = False
ret['comment'] = "Error setting secondary SYSLOG server."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting secondary SYSLOG server."
log.error(err)
return ret
if req_change:
ret['changes']['before'] = conf
ret['changes']['after'] = __salt__['cimc.get_syslog']()
ret['comment'] = "SYSLOG settings modified."
else:
ret['comment'] = "SYSLOG already configured. No changes required."
ret['result'] = True
return ret | [
"def",
"syslog",
"(",
"name",
",",
"primary",
"=",
"None",
",",
"secondary",
"=",
"None",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"conf",
"=",
"__salt__",
"[",
"'cimc.get_syslog'",
"]",
"(",
")",
"req_change",
"=",
"False",
"if",
"prima... | Ensures that the syslog servers are set to the specified values. A value of None will be ignored.
name: The name of the module function to execute.
primary(str): The IP address or FQDN of the primary syslog server.
secondary(str): The IP address or FQDN of the secondary syslog server.
SLS Example:
.. code-block:: yaml
syslog_configuration:
cimc.syslog:
- primary: 10.10.10.10
- secondary: foo.bar.com | [
"Ensures",
"that",
"the",
"syslog",
"servers",
"are",
"set",
"to",
"the",
"specified",
"values",
".",
"A",
"value",
"of",
"None",
"will",
"be",
"ignored",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cimc.py#L351-L434 | train |
saltstack/salt | salt/states/cimc.py | user | def user(name, id='', user='', priv='', password='', status='active'):
'''
Ensures that a user is configured on the device. Due to being unable to
verify the user password. This is a forced operation.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
id(int): The user ID slot on the device.
user(str): The username of the user.
priv(str): The privilege level of the user.
password(str): The password of the user.
status(str): The status of the user. Can be either active or inactive.
SLS Example:
.. code-block:: yaml
user_configuration:
cimc.user:
- id: 11
- user: foo
- priv: admin
- password: mypassword
- status: active
'''
ret = _default_ret(name)
user_conf = __salt__['cimc.get_users']()
try:
for entry in user_conf['outConfigs']['aaaUser']:
if entry['id'] == str(id):
conf = entry
if not conf:
ret['result'] = False
ret['comment'] = "Unable to find requested user id on device. Please verify id is valid."
return ret
updates = __salt__['cimc.set_user'](str(id), user, password, priv, status)
if 'outConfig' in updates:
ret['changes']['before'] = conf
ret['changes']['after'] = updates['outConfig']['aaaUser']
ret['comment'] = "User settings modified."
else:
ret['result'] = False
ret['comment'] = "Error setting user configuration."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting user configuration."
log.error(err)
return ret
ret['result'] = True
return ret | python | def user(name, id='', user='', priv='', password='', status='active'):
'''
Ensures that a user is configured on the device. Due to being unable to
verify the user password. This is a forced operation.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
id(int): The user ID slot on the device.
user(str): The username of the user.
priv(str): The privilege level of the user.
password(str): The password of the user.
status(str): The status of the user. Can be either active or inactive.
SLS Example:
.. code-block:: yaml
user_configuration:
cimc.user:
- id: 11
- user: foo
- priv: admin
- password: mypassword
- status: active
'''
ret = _default_ret(name)
user_conf = __salt__['cimc.get_users']()
try:
for entry in user_conf['outConfigs']['aaaUser']:
if entry['id'] == str(id):
conf = entry
if not conf:
ret['result'] = False
ret['comment'] = "Unable to find requested user id on device. Please verify id is valid."
return ret
updates = __salt__['cimc.set_user'](str(id), user, password, priv, status)
if 'outConfig' in updates:
ret['changes']['before'] = conf
ret['changes']['after'] = updates['outConfig']['aaaUser']
ret['comment'] = "User settings modified."
else:
ret['result'] = False
ret['comment'] = "Error setting user configuration."
return ret
except Exception as err:
ret['result'] = False
ret['comment'] = "Error setting user configuration."
log.error(err)
return ret
ret['result'] = True
return ret | [
"def",
"user",
"(",
"name",
",",
"id",
"=",
"''",
",",
"user",
"=",
"''",
",",
"priv",
"=",
"''",
",",
"password",
"=",
"''",
",",
"status",
"=",
"'active'",
")",
":",
"ret",
"=",
"_default_ret",
"(",
"name",
")",
"user_conf",
"=",
"__salt__",
"[... | Ensures that a user is configured on the device. Due to being unable to
verify the user password. This is a forced operation.
.. versionadded:: 2019.2.0
name: The name of the module function to execute.
id(int): The user ID slot on the device.
user(str): The username of the user.
priv(str): The privilege level of the user.
password(str): The password of the user.
status(str): The status of the user. Can be either active or inactive.
SLS Example:
.. code-block:: yaml
user_configuration:
cimc.user:
- id: 11
- user: foo
- priv: admin
- password: mypassword
- status: active | [
"Ensures",
"that",
"a",
"user",
"is",
"configured",
"on",
"the",
"device",
".",
"Due",
"to",
"being",
"unable",
"to",
"verify",
"the",
"user",
"password",
".",
"This",
"is",
"a",
"forced",
"operation",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/cimc.py#L437-L503 | train |
saltstack/salt | salt/proxy/esxcluster.py | init | def init(opts):
'''
This function gets called when the proxy starts up. For
login
the protocol and port are cached.
'''
log.debug('Initting esxcluster proxy module in process %s', os.getpid())
log.debug('Validating esxcluster proxy input')
schema = EsxclusterProxySchema.serialize()
log.trace('schema = %s', schema)
proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {}))
log.trace('proxy_conf = %s', proxy_conf)
try:
jsonschema.validate(proxy_conf, schema)
except jsonschema.exceptions.ValidationError as exc:
raise salt.exceptions.InvalidConfigError(exc)
# Save mandatory fields in cache
for key in ('vcenter', 'datacenter', 'cluster', 'mechanism'):
DETAILS[key] = proxy_conf[key]
# Additional validation
if DETAILS['mechanism'] == 'userpass':
if 'username' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'userpass\', but no '
'\'username\' key found in proxy config.')
if 'passwords' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'userpass\', but no '
'\'passwords\' key found in proxy config.')
for key in ('username', 'passwords'):
DETAILS[key] = proxy_conf[key]
else:
if 'domain' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'sspi\', but no '
'\'domain\' key found in proxy config.')
if 'principal' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'sspi\', but no '
'\'principal\' key found in proxy config.')
for key in ('domain', 'principal'):
DETAILS[key] = proxy_conf[key]
# Save optional
DETAILS['protocol'] = proxy_conf.get('protocol')
DETAILS['port'] = proxy_conf.get('port')
# Test connection
if DETAILS['mechanism'] == 'userpass':
# Get the correct login details
log.debug('Retrieving credentials and testing vCenter connection for '
'mehchanism \'userpass\'')
try:
username, password = find_credentials()
DETAILS['password'] = password
except salt.exceptions.SaltSystemExit as err:
log.critical('Error: %s', err)
return False
return True | python | def init(opts):
'''
This function gets called when the proxy starts up. For
login
the protocol and port are cached.
'''
log.debug('Initting esxcluster proxy module in process %s', os.getpid())
log.debug('Validating esxcluster proxy input')
schema = EsxclusterProxySchema.serialize()
log.trace('schema = %s', schema)
proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {}))
log.trace('proxy_conf = %s', proxy_conf)
try:
jsonschema.validate(proxy_conf, schema)
except jsonschema.exceptions.ValidationError as exc:
raise salt.exceptions.InvalidConfigError(exc)
# Save mandatory fields in cache
for key in ('vcenter', 'datacenter', 'cluster', 'mechanism'):
DETAILS[key] = proxy_conf[key]
# Additional validation
if DETAILS['mechanism'] == 'userpass':
if 'username' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'userpass\', but no '
'\'username\' key found in proxy config.')
if 'passwords' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'userpass\', but no '
'\'passwords\' key found in proxy config.')
for key in ('username', 'passwords'):
DETAILS[key] = proxy_conf[key]
else:
if 'domain' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'sspi\', but no '
'\'domain\' key found in proxy config.')
if 'principal' not in proxy_conf:
raise salt.exceptions.InvalidConfigError(
'Mechanism is set to \'sspi\', but no '
'\'principal\' key found in proxy config.')
for key in ('domain', 'principal'):
DETAILS[key] = proxy_conf[key]
# Save optional
DETAILS['protocol'] = proxy_conf.get('protocol')
DETAILS['port'] = proxy_conf.get('port')
# Test connection
if DETAILS['mechanism'] == 'userpass':
# Get the correct login details
log.debug('Retrieving credentials and testing vCenter connection for '
'mehchanism \'userpass\'')
try:
username, password = find_credentials()
DETAILS['password'] = password
except salt.exceptions.SaltSystemExit as err:
log.critical('Error: %s', err)
return False
return True | [
"def",
"init",
"(",
"opts",
")",
":",
"log",
".",
"debug",
"(",
"'Initting esxcluster proxy module in process %s'",
",",
"os",
".",
"getpid",
"(",
")",
")",
"log",
".",
"debug",
"(",
"'Validating esxcluster proxy input'",
")",
"schema",
"=",
"EsxclusterProxySchema... | This function gets called when the proxy starts up. For
login
the protocol and port are cached. | [
"This",
"function",
"gets",
"called",
"when",
"the",
"proxy",
"starts",
"up",
".",
"For",
"login",
"the",
"protocol",
"and",
"port",
"are",
"cached",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxcluster.py#L197-L257 | train |
saltstack/salt | salt/proxy/esxcluster.py | find_credentials | def find_credentials():
'''
Cycle through all the possible credentials and return the first one that
works.
'''
# if the username and password were already found don't fo though the
# connection process again
if 'username' in DETAILS and 'password' in DETAILS:
return DETAILS['username'], DETAILS['password']
passwords = DETAILS['passwords']
for password in passwords:
DETAILS['password'] = password
if not __salt__['vsphere.test_vcenter_connection']():
# We are unable to authenticate
continue
# If we have data returned from above, we've successfully authenticated.
return DETAILS['username'], password
# We've reached the end of the list without successfully authenticating.
raise salt.exceptions.VMwareConnectionError('Cannot complete login due to '
'incorrect credentials.') | python | def find_credentials():
'''
Cycle through all the possible credentials and return the first one that
works.
'''
# if the username and password were already found don't fo though the
# connection process again
if 'username' in DETAILS and 'password' in DETAILS:
return DETAILS['username'], DETAILS['password']
passwords = DETAILS['passwords']
for password in passwords:
DETAILS['password'] = password
if not __salt__['vsphere.test_vcenter_connection']():
# We are unable to authenticate
continue
# If we have data returned from above, we've successfully authenticated.
return DETAILS['username'], password
# We've reached the end of the list without successfully authenticating.
raise salt.exceptions.VMwareConnectionError('Cannot complete login due to '
'incorrect credentials.') | [
"def",
"find_credentials",
"(",
")",
":",
"# if the username and password were already found don't fo though the",
"# connection process again",
"if",
"'username'",
"in",
"DETAILS",
"and",
"'password'",
"in",
"DETAILS",
":",
"return",
"DETAILS",
"[",
"'username'",
"]",
",",... | Cycle through all the possible credentials and return the first one that
works. | [
"Cycle",
"through",
"all",
"the",
"possible",
"credentials",
"and",
"return",
"the",
"first",
"one",
"that",
"works",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/esxcluster.py#L281-L302 | train |
saltstack/salt | salt/roster/flat.py | targets | def targets(tgt, tgt_type='glob', **kwargs):
'''
Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster
'''
template = get_roster_file(__opts__)
rend = salt.loader.render(__opts__, {})
raw = compile_template(template,
rend,
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
mask_value='passw*',
**kwargs)
conditioned_raw = {}
for minion in raw:
conditioned_raw[six.text_type(minion)] = salt.config.apply_sdb(raw[minion])
return __utils__['roster_matcher.targets'](conditioned_raw, tgt, tgt_type, 'ipv4') | python | def targets(tgt, tgt_type='glob', **kwargs):
'''
Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster
'''
template = get_roster_file(__opts__)
rend = salt.loader.render(__opts__, {})
raw = compile_template(template,
rend,
__opts__['renderer'],
__opts__['renderer_blacklist'],
__opts__['renderer_whitelist'],
mask_value='passw*',
**kwargs)
conditioned_raw = {}
for minion in raw:
conditioned_raw[six.text_type(minion)] = salt.config.apply_sdb(raw[minion])
return __utils__['roster_matcher.targets'](conditioned_raw, tgt, tgt_type, 'ipv4') | [
"def",
"targets",
"(",
"tgt",
",",
"tgt_type",
"=",
"'glob'",
",",
"*",
"*",
"kwargs",
")",
":",
"template",
"=",
"get_roster_file",
"(",
"__opts__",
")",
"rend",
"=",
"salt",
".",
"loader",
".",
"render",
"(",
"__opts__",
",",
"{",
"}",
")",
"raw",
... | Return the targets from the flat yaml file, checks opts for location but
defaults to /etc/salt/roster | [
"Return",
"the",
"targets",
"from",
"the",
"flat",
"yaml",
"file",
"checks",
"opts",
"for",
"location",
"but",
"defaults",
"to",
"/",
"etc",
"/",
"salt",
"/",
"roster"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/roster/flat.py#L18-L36 | train |
saltstack/salt | salt/cli/key.py | SaltKey.run | def run(self):
'''
Execute salt-key
'''
import salt.key
self.parse_args()
self.setup_logfile_logger()
verify_log(self.config)
key = salt.key.KeyCLI(self.config)
if check_user(self.config['user']):
key.run() | python | def run(self):
'''
Execute salt-key
'''
import salt.key
self.parse_args()
self.setup_logfile_logger()
verify_log(self.config)
key = salt.key.KeyCLI(self.config)
if check_user(self.config['user']):
key.run() | [
"def",
"run",
"(",
"self",
")",
":",
"import",
"salt",
".",
"key",
"self",
".",
"parse_args",
"(",
")",
"self",
".",
"setup_logfile_logger",
"(",
")",
"verify_log",
"(",
"self",
".",
"config",
")",
"key",
"=",
"salt",
".",
"key",
".",
"KeyCLI",
"(",
... | Execute salt-key | [
"Execute",
"salt",
"-",
"key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cli/key.py#L14-L26 | train |
saltstack/salt | salt/sdb/tism.py | get | def get(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a decrypted secret from the tISMd API
'''
if not profile.get('url') or not profile.get('token'):
raise SaltConfigurationError("url and/or token missing from the tism sdb profile")
request = {"token": profile['token'], "encsecret": key}
result = http.query(
profile['url'],
method='POST',
data=salt.utils.json.dumps(request),
)
decrypted = result.get('body')
if not decrypted:
log.warning(
'tism.get sdb decryption request failed with error %s',
result.get('error', 'unknown')
)
return 'ERROR' + six.text_type(result.get('status', 'unknown'))
return decrypted | python | def get(key, service=None, profile=None): # pylint: disable=W0613
'''
Get a decrypted secret from the tISMd API
'''
if not profile.get('url') or not profile.get('token'):
raise SaltConfigurationError("url and/or token missing from the tism sdb profile")
request = {"token": profile['token'], "encsecret": key}
result = http.query(
profile['url'],
method='POST',
data=salt.utils.json.dumps(request),
)
decrypted = result.get('body')
if not decrypted:
log.warning(
'tism.get sdb decryption request failed with error %s',
result.get('error', 'unknown')
)
return 'ERROR' + six.text_type(result.get('status', 'unknown'))
return decrypted | [
"def",
"get",
"(",
"key",
",",
"service",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"# pylint: disable=W0613",
"if",
"not",
"profile",
".",
"get",
"(",
"'url'",
")",
"or",
"not",
"profile",
".",
"get",
"(",
"'token'",
")",
":",
"raise",
"Sa... | Get a decrypted secret from the tISMd API | [
"Get",
"a",
"decrypted",
"secret",
"from",
"the",
"tISMd",
"API"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/tism.py#L53-L78 | train |
saltstack/salt | salt/pillar/postgres.py | ext_pillar | def ext_pillar(minion_id,
pillar,
*args,
**kwargs):
'''
Execute queries against POSTGRES, merge and return as a dict
'''
return POSTGRESExtPillar().fetch(minion_id, pillar, *args, **kwargs) | python | def ext_pillar(minion_id,
pillar,
*args,
**kwargs):
'''
Execute queries against POSTGRES, merge and return as a dict
'''
return POSTGRESExtPillar().fetch(minion_id, pillar, *args, **kwargs) | [
"def",
"ext_pillar",
"(",
"minion_id",
",",
"pillar",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"POSTGRESExtPillar",
"(",
")",
".",
"fetch",
"(",
"minion_id",
",",
"pillar",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Execute queries against POSTGRES, merge and return as a dict | [
"Execute",
"queries",
"against",
"POSTGRES",
"merge",
"and",
"return",
"as",
"a",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/postgres.py#L112-L119 | train |
saltstack/salt | salt/pillar/postgres.py | POSTGRESExtPillar._get_cursor | def _get_cursor(self):
'''
Yield a POSTGRES cursor
'''
_options = self._get_options()
conn = psycopg2.connect(host=_options['host'],
user=_options['user'],
password=_options['pass'],
dbname=_options['db'],
port=_options['port'])
cursor = conn.cursor()
try:
yield cursor
log.debug('Connected to POSTGRES DB')
except psycopg2.DatabaseError as err:
log.exception('Error in ext_pillar POSTGRES: %s', err.args)
finally:
conn.close() | python | def _get_cursor(self):
'''
Yield a POSTGRES cursor
'''
_options = self._get_options()
conn = psycopg2.connect(host=_options['host'],
user=_options['user'],
password=_options['pass'],
dbname=_options['db'],
port=_options['port'])
cursor = conn.cursor()
try:
yield cursor
log.debug('Connected to POSTGRES DB')
except psycopg2.DatabaseError as err:
log.exception('Error in ext_pillar POSTGRES: %s', err.args)
finally:
conn.close() | [
"def",
"_get_cursor",
"(",
"self",
")",
":",
"_options",
"=",
"self",
".",
"_get_options",
"(",
")",
"conn",
"=",
"psycopg2",
".",
"connect",
"(",
"host",
"=",
"_options",
"[",
"'host'",
"]",
",",
"user",
"=",
"_options",
"[",
"'user'",
"]",
",",
"pa... | Yield a POSTGRES cursor | [
"Yield",
"a",
"POSTGRES",
"cursor"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/postgres.py#L85-L102 | train |
saltstack/salt | salt/pillar/postgres.py | POSTGRESExtPillar.extract_queries | def extract_queries(self, args, kwargs):
'''
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
'''
return super(POSTGRESExtPillar, self).extract_queries(args, kwargs) | python | def extract_queries(self, args, kwargs):
'''
This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts.
'''
return super(POSTGRESExtPillar, self).extract_queries(args, kwargs) | [
"def",
"extract_queries",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"return",
"super",
"(",
"POSTGRESExtPillar",
",",
"self",
")",
".",
"extract_queries",
"(",
"args",
",",
"kwargs",
")"
] | This function normalizes the config block into a set of queries we
can use. The return is a list of consistently laid out dicts. | [
"This",
"function",
"normalizes",
"the",
"config",
"block",
"into",
"a",
"set",
"of",
"queries",
"we",
"can",
"use",
".",
"The",
"return",
"is",
"a",
"list",
"of",
"consistently",
"laid",
"out",
"dicts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/postgres.py#L104-L109 | train |
saltstack/salt | salt/modules/ps.py | _get_proc_cmdline | def _get_proc_cmdline(proc):
'''
Returns the cmdline of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.cmdline() if PSUTIL2 else proc.cmdline)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return [] | python | def _get_proc_cmdline(proc):
'''
Returns the cmdline of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.cmdline() if PSUTIL2 else proc.cmdline)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return [] | [
"def",
"_get_proc_cmdline",
"(",
"proc",
")",
":",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"proc",
".",
"cmdline",
"(",
")",
"if",
"PSUTIL2",
"else",
"proc",
".",
"cmdline",
")",
"except",
"(",
"psutil",
".",
"NoS... | Returns the cmdline of a Process instance.
It's backward compatible with < 2.0 versions of psutil. | [
"Returns",
"the",
"cmdline",
"of",
"a",
"Process",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L50-L59 | train |
saltstack/salt | salt/modules/ps.py | _get_proc_create_time | def _get_proc_create_time(proc):
'''
Returns the create_time of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.create_time() if PSUTIL2 else proc.create_time)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return None | python | def _get_proc_create_time(proc):
'''
Returns the create_time of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.create_time() if PSUTIL2 else proc.create_time)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return None | [
"def",
"_get_proc_create_time",
"(",
"proc",
")",
":",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"proc",
".",
"create_time",
"(",
")",
"if",
"PSUTIL2",
"else",
"proc",
".",
"create_time",
")",
"except",
"(",
"psutil",
... | Returns the create_time of a Process instance.
It's backward compatible with < 2.0 versions of psutil. | [
"Returns",
"the",
"create_time",
"of",
"a",
"Process",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L62-L71 | train |
saltstack/salt | salt/modules/ps.py | _get_proc_name | def _get_proc_name(proc):
'''
Returns the name of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.name() if PSUTIL2 else proc.name)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return [] | python | def _get_proc_name(proc):
'''
Returns the name of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.name() if PSUTIL2 else proc.name)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return [] | [
"def",
"_get_proc_name",
"(",
"proc",
")",
":",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"proc",
".",
"name",
"(",
")",
"if",
"PSUTIL2",
"else",
"proc",
".",
"name",
")",
"except",
"(",
"psutil",
".",
"NoSuchProces... | Returns the name of a Process instance.
It's backward compatible with < 2.0 versions of psutil. | [
"Returns",
"the",
"name",
"of",
"a",
"Process",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L74-L83 | train |
saltstack/salt | salt/modules/ps.py | _get_proc_status | def _get_proc_status(proc):
'''
Returns the status of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.status() if PSUTIL2 else proc.status)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return None | python | def _get_proc_status(proc):
'''
Returns the status of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.status() if PSUTIL2 else proc.status)
except (psutil.NoSuchProcess, psutil.AccessDenied):
return None | [
"def",
"_get_proc_status",
"(",
"proc",
")",
":",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"proc",
".",
"status",
"(",
")",
"if",
"PSUTIL2",
"else",
"proc",
".",
"status",
")",
"except",
"(",
"psutil",
".",
"NoSuch... | Returns the status of a Process instance.
It's backward compatible with < 2.0 versions of psutil. | [
"Returns",
"the",
"status",
"of",
"a",
"Process",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L86-L95 | train |
saltstack/salt | salt/modules/ps.py | _get_proc_username | def _get_proc_username(proc):
'''
Returns the username of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.username() if PSUTIL2 else proc.username)
except (psutil.NoSuchProcess, psutil.AccessDenied, KeyError):
return None | python | def _get_proc_username(proc):
'''
Returns the username of a Process instance.
It's backward compatible with < 2.0 versions of psutil.
'''
try:
return salt.utils.data.decode(proc.username() if PSUTIL2 else proc.username)
except (psutil.NoSuchProcess, psutil.AccessDenied, KeyError):
return None | [
"def",
"_get_proc_username",
"(",
"proc",
")",
":",
"try",
":",
"return",
"salt",
".",
"utils",
".",
"data",
".",
"decode",
"(",
"proc",
".",
"username",
"(",
")",
"if",
"PSUTIL2",
"else",
"proc",
".",
"username",
")",
"except",
"(",
"psutil",
".",
"... | Returns the username of a Process instance.
It's backward compatible with < 2.0 versions of psutil. | [
"Returns",
"the",
"username",
"of",
"a",
"Process",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L98-L107 | train |
saltstack/salt | salt/modules/ps.py | top | def top(num_processes=5, interval=3):
'''
Return a list of top CPU consuming processes during the interval.
num_processes = return the top N CPU consuming processes
interval = the number of seconds to sample CPU usage over
CLI Examples:
.. code-block:: bash
salt '*' ps.top
salt '*' ps.top 5 10
'''
result = []
start_usage = {}
for pid in psutil.pids():
try:
process = psutil.Process(pid)
user, system = process.cpu_times()
except ValueError:
user, system, _, _ = process.cpu_times()
except psutil.NoSuchProcess:
continue
start_usage[process] = user + system
time.sleep(interval)
usage = set()
for process, start in six.iteritems(start_usage):
try:
user, system = process.cpu_times()
except ValueError:
user, system, _, _ = process.cpu_times()
except psutil.NoSuchProcess:
continue
now = user + system
diff = now - start
usage.add((diff, process))
for idx, (diff, process) in enumerate(reversed(sorted(usage))):
if num_processes and idx >= num_processes:
break
if not _get_proc_cmdline(process):
cmdline = _get_proc_name(process)
else:
cmdline = _get_proc_cmdline(process)
info = {'cmd': cmdline,
'user': _get_proc_username(process),
'status': _get_proc_status(process),
'pid': _get_proc_pid(process),
'create_time': _get_proc_create_time(process),
'cpu': {},
'mem': {},
}
for key, value in six.iteritems(process.cpu_times()._asdict()):
info['cpu'][key] = value
for key, value in six.iteritems(process.memory_info()._asdict()):
info['mem'][key] = value
result.append(info)
return result | python | def top(num_processes=5, interval=3):
'''
Return a list of top CPU consuming processes during the interval.
num_processes = return the top N CPU consuming processes
interval = the number of seconds to sample CPU usage over
CLI Examples:
.. code-block:: bash
salt '*' ps.top
salt '*' ps.top 5 10
'''
result = []
start_usage = {}
for pid in psutil.pids():
try:
process = psutil.Process(pid)
user, system = process.cpu_times()
except ValueError:
user, system, _, _ = process.cpu_times()
except psutil.NoSuchProcess:
continue
start_usage[process] = user + system
time.sleep(interval)
usage = set()
for process, start in six.iteritems(start_usage):
try:
user, system = process.cpu_times()
except ValueError:
user, system, _, _ = process.cpu_times()
except psutil.NoSuchProcess:
continue
now = user + system
diff = now - start
usage.add((diff, process))
for idx, (diff, process) in enumerate(reversed(sorted(usage))):
if num_processes and idx >= num_processes:
break
if not _get_proc_cmdline(process):
cmdline = _get_proc_name(process)
else:
cmdline = _get_proc_cmdline(process)
info = {'cmd': cmdline,
'user': _get_proc_username(process),
'status': _get_proc_status(process),
'pid': _get_proc_pid(process),
'create_time': _get_proc_create_time(process),
'cpu': {},
'mem': {},
}
for key, value in six.iteritems(process.cpu_times()._asdict()):
info['cpu'][key] = value
for key, value in six.iteritems(process.memory_info()._asdict()):
info['mem'][key] = value
result.append(info)
return result | [
"def",
"top",
"(",
"num_processes",
"=",
"5",
",",
"interval",
"=",
"3",
")",
":",
"result",
"=",
"[",
"]",
"start_usage",
"=",
"{",
"}",
"for",
"pid",
"in",
"psutil",
".",
"pids",
"(",
")",
":",
"try",
":",
"process",
"=",
"psutil",
".",
"Proces... | Return a list of top CPU consuming processes during the interval.
num_processes = return the top N CPU consuming processes
interval = the number of seconds to sample CPU usage over
CLI Examples:
.. code-block:: bash
salt '*' ps.top
salt '*' ps.top 5 10 | [
"Return",
"a",
"list",
"of",
"top",
"CPU",
"consuming",
"processes",
"during",
"the",
"interval",
".",
"num_processes",
"=",
"return",
"the",
"top",
"N",
"CPU",
"consuming",
"processes",
"interval",
"=",
"the",
"number",
"of",
"seconds",
"to",
"sample",
"CPU... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L119-L178 | train |
saltstack/salt | salt/modules/ps.py | proc_info | def proc_info(pid, attrs=None):
'''
Return a dictionary of information for a process id (PID).
CLI Example:
.. code-block:: bash
salt '*' ps.proc_info 2322
salt '*' ps.proc_info 2322 attrs='["pid", "name"]'
pid
PID of process to query.
attrs
Optional list of desired process attributes. The list of possible
attributes can be found here:
http://pythonhosted.org/psutil/#psutil.Process
'''
try:
proc = psutil.Process(pid)
return proc.as_dict(attrs)
except (psutil.NoSuchProcess, psutil.AccessDenied, AttributeError) as exc:
raise CommandExecutionError(exc) | python | def proc_info(pid, attrs=None):
'''
Return a dictionary of information for a process id (PID).
CLI Example:
.. code-block:: bash
salt '*' ps.proc_info 2322
salt '*' ps.proc_info 2322 attrs='["pid", "name"]'
pid
PID of process to query.
attrs
Optional list of desired process attributes. The list of possible
attributes can be found here:
http://pythonhosted.org/psutil/#psutil.Process
'''
try:
proc = psutil.Process(pid)
return proc.as_dict(attrs)
except (psutil.NoSuchProcess, psutil.AccessDenied, AttributeError) as exc:
raise CommandExecutionError(exc) | [
"def",
"proc_info",
"(",
"pid",
",",
"attrs",
"=",
"None",
")",
":",
"try",
":",
"proc",
"=",
"psutil",
".",
"Process",
"(",
"pid",
")",
"return",
"proc",
".",
"as_dict",
"(",
"attrs",
")",
"except",
"(",
"psutil",
".",
"NoSuchProcess",
",",
"psutil"... | Return a dictionary of information for a process id (PID).
CLI Example:
.. code-block:: bash
salt '*' ps.proc_info 2322
salt '*' ps.proc_info 2322 attrs='["pid", "name"]'
pid
PID of process to query.
attrs
Optional list of desired process attributes. The list of possible
attributes can be found here:
http://pythonhosted.org/psutil/#psutil.Process | [
"Return",
"a",
"dictionary",
"of",
"information",
"for",
"a",
"process",
"id",
"(",
"PID",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L194-L217 | train |
saltstack/salt | salt/modules/ps.py | kill_pid | def kill_pid(pid, signal=15):
'''
Kill a process by PID.
.. code-block:: bash
salt 'minion' ps.kill_pid pid [signal=signal_number]
pid
PID of process to kill.
signal
Signal to send to the process. See manpage entry for kill
for possible values. Default: 15 (SIGTERM).
**Example:**
Send SIGKILL to process with PID 2000:
.. code-block:: bash
salt 'minion' ps.kill_pid 2000 signal=9
'''
try:
psutil.Process(pid).send_signal(signal)
return True
except psutil.NoSuchProcess:
return False | python | def kill_pid(pid, signal=15):
'''
Kill a process by PID.
.. code-block:: bash
salt 'minion' ps.kill_pid pid [signal=signal_number]
pid
PID of process to kill.
signal
Signal to send to the process. See manpage entry for kill
for possible values. Default: 15 (SIGTERM).
**Example:**
Send SIGKILL to process with PID 2000:
.. code-block:: bash
salt 'minion' ps.kill_pid 2000 signal=9
'''
try:
psutil.Process(pid).send_signal(signal)
return True
except psutil.NoSuchProcess:
return False | [
"def",
"kill_pid",
"(",
"pid",
",",
"signal",
"=",
"15",
")",
":",
"try",
":",
"psutil",
".",
"Process",
"(",
"pid",
")",
".",
"send_signal",
"(",
"signal",
")",
"return",
"True",
"except",
"psutil",
".",
"NoSuchProcess",
":",
"return",
"False"
] | Kill a process by PID.
.. code-block:: bash
salt 'minion' ps.kill_pid pid [signal=signal_number]
pid
PID of process to kill.
signal
Signal to send to the process. See manpage entry for kill
for possible values. Default: 15 (SIGTERM).
**Example:**
Send SIGKILL to process with PID 2000:
.. code-block:: bash
salt 'minion' ps.kill_pid 2000 signal=9 | [
"Kill",
"a",
"process",
"by",
"PID",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L220-L247 | train |
saltstack/salt | salt/modules/ps.py | pkill | def pkill(pattern, user=None, signal=15, full=False):
'''
Kill processes matching a pattern.
.. code-block:: bash
salt '*' ps.pkill pattern [user=username] [signal=signal_number] \\
[full=(true|false)]
pattern
Pattern to search for in the process list.
user
Limit matches to the given username. Default: All users.
signal
Signal to send to the process(es). See manpage entry for kill
for possible values. Default: 15 (SIGTERM).
full
A boolean value indicating whether only the name of the command or
the full command line should be matched against the pattern.
**Examples:**
Send SIGHUP to all httpd processes on all 'www' minions:
.. code-block:: bash
salt 'www.*' ps.pkill httpd signal=1
Send SIGKILL to all bash processes owned by user 'tom':
.. code-block:: bash
salt '*' ps.pkill bash signal=9 user=tom
'''
killed = []
for proc in psutil.process_iter():
name_match = pattern in ' '.join(_get_proc_cmdline(proc)) if full \
else pattern in _get_proc_name(proc)
user_match = True if user is None else user == _get_proc_username(proc)
if name_match and user_match:
try:
proc.send_signal(signal)
killed.append(_get_proc_pid(proc))
except psutil.NoSuchProcess:
pass
if not killed:
return None
else:
return {'killed': killed} | python | def pkill(pattern, user=None, signal=15, full=False):
'''
Kill processes matching a pattern.
.. code-block:: bash
salt '*' ps.pkill pattern [user=username] [signal=signal_number] \\
[full=(true|false)]
pattern
Pattern to search for in the process list.
user
Limit matches to the given username. Default: All users.
signal
Signal to send to the process(es). See manpage entry for kill
for possible values. Default: 15 (SIGTERM).
full
A boolean value indicating whether only the name of the command or
the full command line should be matched against the pattern.
**Examples:**
Send SIGHUP to all httpd processes on all 'www' minions:
.. code-block:: bash
salt 'www.*' ps.pkill httpd signal=1
Send SIGKILL to all bash processes owned by user 'tom':
.. code-block:: bash
salt '*' ps.pkill bash signal=9 user=tom
'''
killed = []
for proc in psutil.process_iter():
name_match = pattern in ' '.join(_get_proc_cmdline(proc)) if full \
else pattern in _get_proc_name(proc)
user_match = True if user is None else user == _get_proc_username(proc)
if name_match and user_match:
try:
proc.send_signal(signal)
killed.append(_get_proc_pid(proc))
except psutil.NoSuchProcess:
pass
if not killed:
return None
else:
return {'killed': killed} | [
"def",
"pkill",
"(",
"pattern",
",",
"user",
"=",
"None",
",",
"signal",
"=",
"15",
",",
"full",
"=",
"False",
")",
":",
"killed",
"=",
"[",
"]",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
":",
"name_match",
"=",
"pattern",
"in",... | Kill processes matching a pattern.
.. code-block:: bash
salt '*' ps.pkill pattern [user=username] [signal=signal_number] \\
[full=(true|false)]
pattern
Pattern to search for in the process list.
user
Limit matches to the given username. Default: All users.
signal
Signal to send to the process(es). See manpage entry for kill
for possible values. Default: 15 (SIGTERM).
full
A boolean value indicating whether only the name of the command or
the full command line should be matched against the pattern.
**Examples:**
Send SIGHUP to all httpd processes on all 'www' minions:
.. code-block:: bash
salt 'www.*' ps.pkill httpd signal=1
Send SIGKILL to all bash processes owned by user 'tom':
.. code-block:: bash
salt '*' ps.pkill bash signal=9 user=tom | [
"Kill",
"processes",
"matching",
"a",
"pattern",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L250-L302 | train |
saltstack/salt | salt/modules/ps.py | pgrep | def pgrep(pattern, user=None, full=False, pattern_is_regex=False):
'''
Return the pids for processes matching a pattern.
If full is true, the full command line is searched for a match,
otherwise only the name of the command is searched.
.. code-block:: bash
salt '*' ps.pgrep pattern [user=username] [full=(true|false)]
pattern
Pattern to search for in the process list.
user
Limit matches to the given username. Default: All users.
full
A boolean value indicating whether only the name of the command or
the full command line should be matched against the pattern.
pattern_is_regex
This flag enables ps.pgrep to mirror the regex search functionality
found in the pgrep command line utility.
.. versionadded:: Neon
**Examples:**
Find all httpd processes on all 'www' minions:
.. code-block:: bash
salt 'www.*' ps.pgrep httpd
Find all bash processes owned by user 'tom':
.. code-block:: bash
salt '*' ps.pgrep bash user=tom
'''
procs = []
if pattern_is_regex:
pattern = re.compile(str(pattern))
procs = []
for proc in psutil.process_iter():
if full:
process_line = ' '.join(_get_proc_cmdline(proc))
else:
process_line = _get_proc_name(proc)
if pattern_is_regex:
name_match = re.search(pattern, process_line)
else:
name_match = pattern in process_line
user_match = True if user is None else user == _get_proc_username(proc)
if name_match and user_match:
procs.append(_get_proc_pid(proc))
return procs or None | python | def pgrep(pattern, user=None, full=False, pattern_is_regex=False):
'''
Return the pids for processes matching a pattern.
If full is true, the full command line is searched for a match,
otherwise only the name of the command is searched.
.. code-block:: bash
salt '*' ps.pgrep pattern [user=username] [full=(true|false)]
pattern
Pattern to search for in the process list.
user
Limit matches to the given username. Default: All users.
full
A boolean value indicating whether only the name of the command or
the full command line should be matched against the pattern.
pattern_is_regex
This flag enables ps.pgrep to mirror the regex search functionality
found in the pgrep command line utility.
.. versionadded:: Neon
**Examples:**
Find all httpd processes on all 'www' minions:
.. code-block:: bash
salt 'www.*' ps.pgrep httpd
Find all bash processes owned by user 'tom':
.. code-block:: bash
salt '*' ps.pgrep bash user=tom
'''
procs = []
if pattern_is_regex:
pattern = re.compile(str(pattern))
procs = []
for proc in psutil.process_iter():
if full:
process_line = ' '.join(_get_proc_cmdline(proc))
else:
process_line = _get_proc_name(proc)
if pattern_is_regex:
name_match = re.search(pattern, process_line)
else:
name_match = pattern in process_line
user_match = True if user is None else user == _get_proc_username(proc)
if name_match and user_match:
procs.append(_get_proc_pid(proc))
return procs or None | [
"def",
"pgrep",
"(",
"pattern",
",",
"user",
"=",
"None",
",",
"full",
"=",
"False",
",",
"pattern_is_regex",
"=",
"False",
")",
":",
"procs",
"=",
"[",
"]",
"if",
"pattern_is_regex",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"str",
"(",
"patte... | Return the pids for processes matching a pattern.
If full is true, the full command line is searched for a match,
otherwise only the name of the command is searched.
.. code-block:: bash
salt '*' ps.pgrep pattern [user=username] [full=(true|false)]
pattern
Pattern to search for in the process list.
user
Limit matches to the given username. Default: All users.
full
A boolean value indicating whether only the name of the command or
the full command line should be matched against the pattern.
pattern_is_regex
This flag enables ps.pgrep to mirror the regex search functionality
found in the pgrep command line utility.
.. versionadded:: Neon
**Examples:**
Find all httpd processes on all 'www' minions:
.. code-block:: bash
salt 'www.*' ps.pgrep httpd
Find all bash processes owned by user 'tom':
.. code-block:: bash
salt '*' ps.pgrep bash user=tom | [
"Return",
"the",
"pids",
"for",
"processes",
"matching",
"a",
"pattern",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L305-L368 | train |
saltstack/salt | salt/modules/ps.py | cpu_percent | def cpu_percent(interval=0.1, per_cpu=False):
'''
Return the percent of time the CPU is busy.
interval
the number of seconds to sample CPU usage over
per_cpu
if True return an array of CPU percent busy for each CPU, otherwise
aggregate all percents into one number
CLI Example:
.. code-block:: bash
salt '*' ps.cpu_percent
'''
if per_cpu:
result = list(psutil.cpu_percent(interval, True))
else:
result = psutil.cpu_percent(interval)
return result | python | def cpu_percent(interval=0.1, per_cpu=False):
'''
Return the percent of time the CPU is busy.
interval
the number of seconds to sample CPU usage over
per_cpu
if True return an array of CPU percent busy for each CPU, otherwise
aggregate all percents into one number
CLI Example:
.. code-block:: bash
salt '*' ps.cpu_percent
'''
if per_cpu:
result = list(psutil.cpu_percent(interval, True))
else:
result = psutil.cpu_percent(interval)
return result | [
"def",
"cpu_percent",
"(",
"interval",
"=",
"0.1",
",",
"per_cpu",
"=",
"False",
")",
":",
"if",
"per_cpu",
":",
"result",
"=",
"list",
"(",
"psutil",
".",
"cpu_percent",
"(",
"interval",
",",
"True",
")",
")",
"else",
":",
"result",
"=",
"psutil",
"... | Return the percent of time the CPU is busy.
interval
the number of seconds to sample CPU usage over
per_cpu
if True return an array of CPU percent busy for each CPU, otherwise
aggregate all percents into one number
CLI Example:
.. code-block:: bash
salt '*' ps.cpu_percent | [
"Return",
"the",
"percent",
"of",
"time",
"the",
"CPU",
"is",
"busy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L371-L391 | train |
saltstack/salt | salt/modules/ps.py | cpu_times | def cpu_times(per_cpu=False):
'''
Return the percent of time the CPU spends in each state,
e.g. user, system, idle, nice, iowait, irq, softirq.
per_cpu
if True return an array of percents for each CPU, otherwise aggregate
all percents into one number
CLI Example:
.. code-block:: bash
salt '*' ps.cpu_times
'''
if per_cpu:
result = [dict(times._asdict()) for times in psutil.cpu_times(True)]
else:
result = dict(psutil.cpu_times(per_cpu)._asdict())
return result | python | def cpu_times(per_cpu=False):
'''
Return the percent of time the CPU spends in each state,
e.g. user, system, idle, nice, iowait, irq, softirq.
per_cpu
if True return an array of percents for each CPU, otherwise aggregate
all percents into one number
CLI Example:
.. code-block:: bash
salt '*' ps.cpu_times
'''
if per_cpu:
result = [dict(times._asdict()) for times in psutil.cpu_times(True)]
else:
result = dict(psutil.cpu_times(per_cpu)._asdict())
return result | [
"def",
"cpu_times",
"(",
"per_cpu",
"=",
"False",
")",
":",
"if",
"per_cpu",
":",
"result",
"=",
"[",
"dict",
"(",
"times",
".",
"_asdict",
"(",
")",
")",
"for",
"times",
"in",
"psutil",
".",
"cpu_times",
"(",
"True",
")",
"]",
"else",
":",
"result... | Return the percent of time the CPU spends in each state,
e.g. user, system, idle, nice, iowait, irq, softirq.
per_cpu
if True return an array of percents for each CPU, otherwise aggregate
all percents into one number
CLI Example:
.. code-block:: bash
salt '*' ps.cpu_times | [
"Return",
"the",
"percent",
"of",
"time",
"the",
"CPU",
"spends",
"in",
"each",
"state",
"e",
".",
"g",
".",
"user",
"system",
"idle",
"nice",
"iowait",
"irq",
"softirq",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L394-L413 | train |
saltstack/salt | salt/modules/ps.py | virtual_memory | def virtual_memory():
'''
.. versionadded:: 2014.7.0
Return a dict that describes statistics about system memory usage.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.virtual_memory
'''
if psutil.version_info < (0, 6, 0):
msg = 'virtual_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError(msg)
return dict(psutil.virtual_memory()._asdict()) | python | def virtual_memory():
'''
.. versionadded:: 2014.7.0
Return a dict that describes statistics about system memory usage.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.virtual_memory
'''
if psutil.version_info < (0, 6, 0):
msg = 'virtual_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError(msg)
return dict(psutil.virtual_memory()._asdict()) | [
"def",
"virtual_memory",
"(",
")",
":",
"if",
"psutil",
".",
"version_info",
"<",
"(",
"0",
",",
"6",
",",
"0",
")",
":",
"msg",
"=",
"'virtual_memory is only available in psutil 0.6.0 or greater'",
"raise",
"CommandExecutionError",
"(",
"msg",
")",
"return",
"d... | .. versionadded:: 2014.7.0
Return a dict that describes statistics about system memory usage.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.virtual_memory | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L416-L435 | train |
saltstack/salt | salt/modules/ps.py | swap_memory | def swap_memory():
'''
.. versionadded:: 2014.7.0
Return a dict that describes swap memory statistics.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.swap_memory
'''
if psutil.version_info < (0, 6, 0):
msg = 'swap_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError(msg)
return dict(psutil.swap_memory()._asdict()) | python | def swap_memory():
'''
.. versionadded:: 2014.7.0
Return a dict that describes swap memory statistics.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.swap_memory
'''
if psutil.version_info < (0, 6, 0):
msg = 'swap_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError(msg)
return dict(psutil.swap_memory()._asdict()) | [
"def",
"swap_memory",
"(",
")",
":",
"if",
"psutil",
".",
"version_info",
"<",
"(",
"0",
",",
"6",
",",
"0",
")",
":",
"msg",
"=",
"'swap_memory is only available in psutil 0.6.0 or greater'",
"raise",
"CommandExecutionError",
"(",
"msg",
")",
"return",
"dict",
... | .. versionadded:: 2014.7.0
Return a dict that describes swap memory statistics.
.. note::
This function is only available in psutil version 0.6.0 and above.
CLI Example:
.. code-block:: bash
salt '*' ps.swap_memory | [
"..",
"versionadded",
"::",
"2014",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L438-L457 | train |
saltstack/salt | salt/modules/ps.py | disk_partitions | def disk_partitions(all=False):
'''
Return a list of disk partitions and their device, mount point, and
filesystem type.
all
if set to False, only return local, physical partitions (hard disk,
USB, CD/DVD partitions). If True, return all filesystems.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_partitions
'''
result = [dict(partition._asdict()) for partition in
psutil.disk_partitions(all)]
return result | python | def disk_partitions(all=False):
'''
Return a list of disk partitions and their device, mount point, and
filesystem type.
all
if set to False, only return local, physical partitions (hard disk,
USB, CD/DVD partitions). If True, return all filesystems.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_partitions
'''
result = [dict(partition._asdict()) for partition in
psutil.disk_partitions(all)]
return result | [
"def",
"disk_partitions",
"(",
"all",
"=",
"False",
")",
":",
"result",
"=",
"[",
"dict",
"(",
"partition",
".",
"_asdict",
"(",
")",
")",
"for",
"partition",
"in",
"psutil",
".",
"disk_partitions",
"(",
"all",
")",
"]",
"return",
"result"
] | Return a list of disk partitions and their device, mount point, and
filesystem type.
all
if set to False, only return local, physical partitions (hard disk,
USB, CD/DVD partitions). If True, return all filesystems.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_partitions | [
"Return",
"a",
"list",
"of",
"disk",
"partitions",
"and",
"their",
"device",
"mount",
"point",
"and",
"filesystem",
"type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L460-L477 | train |
saltstack/salt | salt/modules/ps.py | disk_partition_usage | def disk_partition_usage(all=False):
'''
Return a list of disk partitions plus the mount point, filesystem and usage
statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_partition_usage
'''
result = disk_partitions(all)
for partition in result:
partition.update(disk_usage(partition['mountpoint']))
return result | python | def disk_partition_usage(all=False):
'''
Return a list of disk partitions plus the mount point, filesystem and usage
statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_partition_usage
'''
result = disk_partitions(all)
for partition in result:
partition.update(disk_usage(partition['mountpoint']))
return result | [
"def",
"disk_partition_usage",
"(",
"all",
"=",
"False",
")",
":",
"result",
"=",
"disk_partitions",
"(",
"all",
")",
"for",
"partition",
"in",
"result",
":",
"partition",
".",
"update",
"(",
"disk_usage",
"(",
"partition",
"[",
"'mountpoint'",
"]",
")",
"... | Return a list of disk partitions plus the mount point, filesystem and usage
statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_partition_usage | [
"Return",
"a",
"list",
"of",
"disk",
"partitions",
"plus",
"the",
"mount",
"point",
"filesystem",
"and",
"usage",
"statistics",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L494-L508 | train |
saltstack/salt | salt/modules/ps.py | total_physical_memory | def total_physical_memory():
'''
Return the total number of bytes of physical memory.
CLI Example:
.. code-block:: bash
salt '*' ps.total_physical_memory
'''
if psutil.version_info < (0, 6, 0):
msg = 'virtual_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError(msg)
try:
return psutil.virtual_memory().total
except AttributeError:
# TOTAL_PHYMEM is deprecated but with older psutil versions this is
# needed as a fallback.
return psutil.TOTAL_PHYMEM | python | def total_physical_memory():
'''
Return the total number of bytes of physical memory.
CLI Example:
.. code-block:: bash
salt '*' ps.total_physical_memory
'''
if psutil.version_info < (0, 6, 0):
msg = 'virtual_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError(msg)
try:
return psutil.virtual_memory().total
except AttributeError:
# TOTAL_PHYMEM is deprecated but with older psutil versions this is
# needed as a fallback.
return psutil.TOTAL_PHYMEM | [
"def",
"total_physical_memory",
"(",
")",
":",
"if",
"psutil",
".",
"version_info",
"<",
"(",
"0",
",",
"6",
",",
"0",
")",
":",
"msg",
"=",
"'virtual_memory is only available in psutil 0.6.0 or greater'",
"raise",
"CommandExecutionError",
"(",
"msg",
")",
"try",
... | Return the total number of bytes of physical memory.
CLI Example:
.. code-block:: bash
salt '*' ps.total_physical_memory | [
"Return",
"the",
"total",
"number",
"of",
"bytes",
"of",
"physical",
"memory",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L511-L529 | train |
saltstack/salt | salt/modules/ps.py | boot_time | def boot_time(time_format=None):
'''
Return the boot time in number of seconds since the epoch began.
CLI Example:
time_format
Optionally specify a `strftime`_ format string. Use
``time_format='%c'`` to get a nicely-formatted locale specific date and
time (i.e. ``Fri May 2 19:08:32 2014``).
.. _strftime: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
.. versionadded:: 2014.1.4
.. code-block:: bash
salt '*' ps.boot_time
'''
try:
b_time = int(psutil.boot_time())
except AttributeError:
# get_boot_time() has been removed in newer psutil versions, and has
# been replaced by boot_time() which provides the same information.
b_time = int(psutil.boot_time())
if time_format:
# Load epoch timestamp as a datetime.datetime object
b_time = datetime.datetime.fromtimestamp(b_time)
try:
return b_time.strftime(time_format)
except TypeError as exc:
raise SaltInvocationError('Invalid format string: {0}'.format(exc))
return b_time | python | def boot_time(time_format=None):
'''
Return the boot time in number of seconds since the epoch began.
CLI Example:
time_format
Optionally specify a `strftime`_ format string. Use
``time_format='%c'`` to get a nicely-formatted locale specific date and
time (i.e. ``Fri May 2 19:08:32 2014``).
.. _strftime: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
.. versionadded:: 2014.1.4
.. code-block:: bash
salt '*' ps.boot_time
'''
try:
b_time = int(psutil.boot_time())
except AttributeError:
# get_boot_time() has been removed in newer psutil versions, and has
# been replaced by boot_time() which provides the same information.
b_time = int(psutil.boot_time())
if time_format:
# Load epoch timestamp as a datetime.datetime object
b_time = datetime.datetime.fromtimestamp(b_time)
try:
return b_time.strftime(time_format)
except TypeError as exc:
raise SaltInvocationError('Invalid format string: {0}'.format(exc))
return b_time | [
"def",
"boot_time",
"(",
"time_format",
"=",
"None",
")",
":",
"try",
":",
"b_time",
"=",
"int",
"(",
"psutil",
".",
"boot_time",
"(",
")",
")",
"except",
"AttributeError",
":",
"# get_boot_time() has been removed in newer psutil versions, and has",
"# been replaced b... | Return the boot time in number of seconds since the epoch began.
CLI Example:
time_format
Optionally specify a `strftime`_ format string. Use
``time_format='%c'`` to get a nicely-formatted locale specific date and
time (i.e. ``Fri May 2 19:08:32 2014``).
.. _strftime: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
.. versionadded:: 2014.1.4
.. code-block:: bash
salt '*' ps.boot_time | [
"Return",
"the",
"boot",
"time",
"in",
"number",
"of",
"seconds",
"since",
"the",
"epoch",
"began",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L550-L582 | train |
saltstack/salt | salt/modules/ps.py | network_io_counters | def network_io_counters(interface=None):
'''
Return network I/O statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.network_io_counters
salt '*' ps.network_io_counters interface=eth0
'''
if not interface:
return dict(psutil.net_io_counters()._asdict())
else:
stats = psutil.net_io_counters(pernic=True)
if interface in stats:
return dict(stats[interface]._asdict())
else:
return False | python | def network_io_counters(interface=None):
'''
Return network I/O statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.network_io_counters
salt '*' ps.network_io_counters interface=eth0
'''
if not interface:
return dict(psutil.net_io_counters()._asdict())
else:
stats = psutil.net_io_counters(pernic=True)
if interface in stats:
return dict(stats[interface]._asdict())
else:
return False | [
"def",
"network_io_counters",
"(",
"interface",
"=",
"None",
")",
":",
"if",
"not",
"interface",
":",
"return",
"dict",
"(",
"psutil",
".",
"net_io_counters",
"(",
")",
".",
"_asdict",
"(",
")",
")",
"else",
":",
"stats",
"=",
"psutil",
".",
"net_io_coun... | Return network I/O statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.network_io_counters
salt '*' ps.network_io_counters interface=eth0 | [
"Return",
"network",
"I",
"/",
"O",
"statistics",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L585-L604 | train |
saltstack/salt | salt/modules/ps.py | disk_io_counters | def disk_io_counters(device=None):
'''
Return disk I/O statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_io_counters
salt '*' ps.disk_io_counters device=sda1
'''
if not device:
return dict(psutil.disk_io_counters()._asdict())
else:
stats = psutil.disk_io_counters(perdisk=True)
if device in stats:
return dict(stats[device]._asdict())
else:
return False | python | def disk_io_counters(device=None):
'''
Return disk I/O statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_io_counters
salt '*' ps.disk_io_counters device=sda1
'''
if not device:
return dict(psutil.disk_io_counters()._asdict())
else:
stats = psutil.disk_io_counters(perdisk=True)
if device in stats:
return dict(stats[device]._asdict())
else:
return False | [
"def",
"disk_io_counters",
"(",
"device",
"=",
"None",
")",
":",
"if",
"not",
"device",
":",
"return",
"dict",
"(",
"psutil",
".",
"disk_io_counters",
"(",
")",
".",
"_asdict",
"(",
")",
")",
"else",
":",
"stats",
"=",
"psutil",
".",
"disk_io_counters",
... | Return disk I/O statistics.
CLI Example:
.. code-block:: bash
salt '*' ps.disk_io_counters
salt '*' ps.disk_io_counters device=sda1 | [
"Return",
"disk",
"I",
"/",
"O",
"statistics",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L607-L626 | train |
saltstack/salt | salt/modules/ps.py | get_users | def get_users():
'''
Return logged-in users.
CLI Example:
.. code-block:: bash
salt '*' ps.get_users
'''
try:
recs = psutil.users()
return [dict(x._asdict()) for x in recs]
except AttributeError:
# get_users is only present in psutil > v0.5.0
# try utmp
try:
import utmp # pylint: disable=import-error
result = []
while True:
rec = utmp.utmpaccess.getutent()
if rec is None:
return result
elif rec[0] == 7:
started = rec[8]
if isinstance(started, tuple):
started = started[0]
result.append({'name': rec[4], 'terminal': rec[2],
'started': started, 'host': rec[5]})
except ImportError:
return False | python | def get_users():
'''
Return logged-in users.
CLI Example:
.. code-block:: bash
salt '*' ps.get_users
'''
try:
recs = psutil.users()
return [dict(x._asdict()) for x in recs]
except AttributeError:
# get_users is only present in psutil > v0.5.0
# try utmp
try:
import utmp # pylint: disable=import-error
result = []
while True:
rec = utmp.utmpaccess.getutent()
if rec is None:
return result
elif rec[0] == 7:
started = rec[8]
if isinstance(started, tuple):
started = started[0]
result.append({'name': rec[4], 'terminal': rec[2],
'started': started, 'host': rec[5]})
except ImportError:
return False | [
"def",
"get_users",
"(",
")",
":",
"try",
":",
"recs",
"=",
"psutil",
".",
"users",
"(",
")",
"return",
"[",
"dict",
"(",
"x",
".",
"_asdict",
"(",
")",
")",
"for",
"x",
"in",
"recs",
"]",
"except",
"AttributeError",
":",
"# get_users is only present i... | Return logged-in users.
CLI Example:
.. code-block:: bash
salt '*' ps.get_users | [
"Return",
"logged",
"-",
"in",
"users",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L629-L660 | train |
saltstack/salt | salt/modules/ps.py | lsof | def lsof(name):
'''
Retrieve the lsof information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.lsof apache2
'''
sanitize_name = six.text_type(name)
lsof_infos = __salt__['cmd.run']("lsof -c " + sanitize_name)
ret = []
ret.extend([sanitize_name, lsof_infos])
return ret | python | def lsof(name):
'''
Retrieve the lsof information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.lsof apache2
'''
sanitize_name = six.text_type(name)
lsof_infos = __salt__['cmd.run']("lsof -c " + sanitize_name)
ret = []
ret.extend([sanitize_name, lsof_infos])
return ret | [
"def",
"lsof",
"(",
"name",
")",
":",
"sanitize_name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
"lsof_infos",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"\"lsof -c \"",
"+",
"sanitize_name",
")",
"ret",
"=",
"[",
"]",
"ret",
".",
"extend",
"("... | Retrieve the lsof information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.lsof apache2 | [
"Retrieve",
"the",
"lsof",
"information",
"of",
"the",
"given",
"process",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L663-L677 | train |
saltstack/salt | salt/modules/ps.py | netstat | def netstat(name):
'''
Retrieve the netstat information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.netstat apache2
'''
sanitize_name = six.text_type(name)
netstat_infos = __salt__['cmd.run']("netstat -nap")
found_infos = []
ret = []
for info in netstat_infos.splitlines():
if info.find(sanitize_name) != -1:
found_infos.append(info)
ret.extend([sanitize_name, found_infos])
return ret | python | def netstat(name):
'''
Retrieve the netstat information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.netstat apache2
'''
sanitize_name = six.text_type(name)
netstat_infos = __salt__['cmd.run']("netstat -nap")
found_infos = []
ret = []
for info in netstat_infos.splitlines():
if info.find(sanitize_name) != -1:
found_infos.append(info)
ret.extend([sanitize_name, found_infos])
return ret | [
"def",
"netstat",
"(",
"name",
")",
":",
"sanitize_name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
"netstat_infos",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"\"netstat -nap\"",
")",
"found_infos",
"=",
"[",
"]",
"ret",
"=",
"[",
"]",
"for",
... | Retrieve the netstat information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.netstat apache2 | [
"Retrieve",
"the",
"netstat",
"information",
"of",
"the",
"given",
"process",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L681-L699 | train |
saltstack/salt | salt/modules/ps.py | ss | def ss(name):
'''
Retrieve the ss information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.ss apache2
.. versionadded:: 2016.11.6
'''
sanitize_name = six.text_type(name)
ss_infos = __salt__['cmd.run']("ss -neap")
found_infos = []
ret = []
for info in ss_infos.splitlines():
if info.find(sanitize_name) != -1:
found_infos.append(info)
ret.extend([sanitize_name, found_infos])
return ret | python | def ss(name):
'''
Retrieve the ss information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.ss apache2
.. versionadded:: 2016.11.6
'''
sanitize_name = six.text_type(name)
ss_infos = __salt__['cmd.run']("ss -neap")
found_infos = []
ret = []
for info in ss_infos.splitlines():
if info.find(sanitize_name) != -1:
found_infos.append(info)
ret.extend([sanitize_name, found_infos])
return ret | [
"def",
"ss",
"(",
"name",
")",
":",
"sanitize_name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
"ss_infos",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"\"ss -neap\"",
")",
"found_infos",
"=",
"[",
"]",
"ret",
"=",
"[",
"]",
"for",
"info",
"in"... | Retrieve the ss information of the given process name.
CLI Example:
.. code-block:: bash
salt '*' ps.ss apache2
.. versionadded:: 2016.11.6 | [
"Retrieve",
"the",
"ss",
"information",
"of",
"the",
"given",
"process",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L703-L724 | train |
saltstack/salt | salt/modules/ps.py | psaux | def psaux(name):
'''
Retrieve information corresponding to a "ps aux" filtered
with the given pattern. It could be just a name or a regular
expression (using python search from "re" module).
CLI Example:
.. code-block:: bash
salt '*' ps.psaux www-data.+apache2
'''
sanitize_name = six.text_type(name)
pattern = re.compile(sanitize_name)
salt_exception_pattern = re.compile("salt.+ps.psaux.+")
ps_aux = __salt__['cmd.run']("ps aux")
found_infos = []
ret = []
nb_lines = 0
for info in ps_aux.splitlines():
found = pattern.search(info)
if found is not None:
# remove 'salt' command from results
if not salt_exception_pattern.search(info):
nb_lines += 1
found_infos.append(info)
pid_count = six.text_type(nb_lines) + " occurence(s)."
ret = []
ret.extend([sanitize_name, found_infos, pid_count])
return ret | python | def psaux(name):
'''
Retrieve information corresponding to a "ps aux" filtered
with the given pattern. It could be just a name or a regular
expression (using python search from "re" module).
CLI Example:
.. code-block:: bash
salt '*' ps.psaux www-data.+apache2
'''
sanitize_name = six.text_type(name)
pattern = re.compile(sanitize_name)
salt_exception_pattern = re.compile("salt.+ps.psaux.+")
ps_aux = __salt__['cmd.run']("ps aux")
found_infos = []
ret = []
nb_lines = 0
for info in ps_aux.splitlines():
found = pattern.search(info)
if found is not None:
# remove 'salt' command from results
if not salt_exception_pattern.search(info):
nb_lines += 1
found_infos.append(info)
pid_count = six.text_type(nb_lines) + " occurence(s)."
ret = []
ret.extend([sanitize_name, found_infos, pid_count])
return ret | [
"def",
"psaux",
"(",
"name",
")",
":",
"sanitize_name",
"=",
"six",
".",
"text_type",
"(",
"name",
")",
"pattern",
"=",
"re",
".",
"compile",
"(",
"sanitize_name",
")",
"salt_exception_pattern",
"=",
"re",
".",
"compile",
"(",
"\"salt.+ps.psaux.+\"",
")",
... | Retrieve information corresponding to a "ps aux" filtered
with the given pattern. It could be just a name or a regular
expression (using python search from "re" module).
CLI Example:
.. code-block:: bash
salt '*' ps.psaux www-data.+apache2 | [
"Retrieve",
"information",
"corresponding",
"to",
"a",
"ps",
"aux",
"filtered",
"with",
"the",
"given",
"pattern",
".",
"It",
"could",
"be",
"just",
"a",
"name",
"or",
"a",
"regular",
"expression",
"(",
"using",
"python",
"search",
"from",
"re",
"module",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/ps.py#L727-L756 | train |
saltstack/salt | salt/states/pagerduty_service.py | present | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty service exists.
This method accepts as arguments everything defined in
https://developer.pagerduty.com/documentation/rest/services/create
Note that many arguments are mutually exclusive, depending on the "type" argument.
Examples:
.. code-block:: yaml
# create a PagerDuty email service at test-email@DOMAIN.pagerduty.com
ensure generic email service exists:
pagerduty_service.present:
- name: my email service
- service:
description: "email service controlled by salt"
escalation_policy_id: "my escalation policy"
type: "generic_email"
service_key: "test-email"
.. code-block:: yaml
# create a pagerduty service using cloudwatch integration
ensure my cloudwatch service exists:
pagerduty_service.present:
- name: my cloudwatch service
- service:
escalation_policy_id: "my escalation policy"
type: aws_cloudwatch
description: "my cloudwatch service controlled by salt"
'''
# TODO: aws_cloudwatch type should be integrated with boto_sns
# for convenience, we accept id, name, or email for users
# and we accept the id or name for schedules
kwargs['service']['name'] = kwargs['name'] # make args mirror PD API structure
escalation_policy_id = kwargs['service']['escalation_policy_id']
escalation_policy = __salt__['pagerduty_util.get_resource']('escalation_policies',
escalation_policy_id,
['name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if escalation_policy:
kwargs['service']['escalation_policy_id'] = escalation_policy['id']
r = __salt__['pagerduty_util.resource_present']('services',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r | python | def present(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure pagerduty service exists.
This method accepts as arguments everything defined in
https://developer.pagerduty.com/documentation/rest/services/create
Note that many arguments are mutually exclusive, depending on the "type" argument.
Examples:
.. code-block:: yaml
# create a PagerDuty email service at test-email@DOMAIN.pagerduty.com
ensure generic email service exists:
pagerduty_service.present:
- name: my email service
- service:
description: "email service controlled by salt"
escalation_policy_id: "my escalation policy"
type: "generic_email"
service_key: "test-email"
.. code-block:: yaml
# create a pagerduty service using cloudwatch integration
ensure my cloudwatch service exists:
pagerduty_service.present:
- name: my cloudwatch service
- service:
escalation_policy_id: "my escalation policy"
type: aws_cloudwatch
description: "my cloudwatch service controlled by salt"
'''
# TODO: aws_cloudwatch type should be integrated with boto_sns
# for convenience, we accept id, name, or email for users
# and we accept the id or name for schedules
kwargs['service']['name'] = kwargs['name'] # make args mirror PD API structure
escalation_policy_id = kwargs['service']['escalation_policy_id']
escalation_policy = __salt__['pagerduty_util.get_resource']('escalation_policies',
escalation_policy_id,
['name', 'id'],
profile=profile,
subdomain=subdomain,
api_key=api_key)
if escalation_policy:
kwargs['service']['escalation_policy_id'] = escalation_policy['id']
r = __salt__['pagerduty_util.resource_present']('services',
['name', 'id'],
_diff,
profile,
subdomain,
api_key,
**kwargs)
return r | [
"def",
"present",
"(",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: aws_cloudwatch type should be integrated with boto_sns",
"# for convenience, we accept id, name, or email for users"... | Ensure pagerduty service exists.
This method accepts as arguments everything defined in
https://developer.pagerduty.com/documentation/rest/services/create
Note that many arguments are mutually exclusive, depending on the "type" argument.
Examples:
.. code-block:: yaml
# create a PagerDuty email service at test-email@DOMAIN.pagerduty.com
ensure generic email service exists:
pagerduty_service.present:
- name: my email service
- service:
description: "email service controlled by salt"
escalation_policy_id: "my escalation policy"
type: "generic_email"
service_key: "test-email"
.. code-block:: yaml
# create a pagerduty service using cloudwatch integration
ensure my cloudwatch service exists:
pagerduty_service.present:
- name: my cloudwatch service
- service:
escalation_policy_id: "my escalation policy"
type: aws_cloudwatch
description: "my cloudwatch service controlled by salt" | [
"Ensure",
"pagerduty",
"service",
"exists",
".",
"This",
"method",
"accepts",
"as",
"arguments",
"everything",
"defined",
"in",
"https",
":",
"//",
"developer",
".",
"pagerduty",
".",
"com",
"/",
"documentation",
"/",
"rest",
"/",
"services",
"/",
"create"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_service.py#L30-L84 | train |
saltstack/salt | salt/states/pagerduty_service.py | absent | def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure a pagerduty service does not exist.
Name can be the service name or pagerduty service id.
'''
r = __salt__['pagerduty_util.resource_absent']('services',
['name', 'id'],
profile,
subdomain,
api_key,
**kwargs)
return r | python | def absent(profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Ensure a pagerduty service does not exist.
Name can be the service name or pagerduty service id.
'''
r = __salt__['pagerduty_util.resource_absent']('services',
['name', 'id'],
profile,
subdomain,
api_key,
**kwargs)
return r | [
"def",
"absent",
"(",
"profile",
"=",
"'pagerduty'",
",",
"subdomain",
"=",
"None",
",",
"api_key",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"__salt__",
"[",
"'pagerduty_util.resource_absent'",
"]",
"(",
"'services'",
",",
"[",
"'name'",
... | Ensure a pagerduty service does not exist.
Name can be the service name or pagerduty service id. | [
"Ensure",
"a",
"pagerduty",
"service",
"does",
"not",
"exist",
".",
"Name",
"can",
"be",
"the",
"service",
"name",
"or",
"pagerduty",
"service",
"id",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_service.py#L87-L98 | train |
saltstack/salt | salt/states/pagerduty_service.py | _diff | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
objects_differ = None
for k, v in state_data['service'].items():
if k == 'escalation_policy_id':
resource_value = resource_object['escalation_policy']['id']
elif k == 'service_key':
# service_key on create must 'foo' but the GET will return 'foo@bar.pagerduty.com'
resource_value = resource_object['service_key']
if '@' in resource_value:
resource_value = resource_value[0:resource_value.find('@')]
else:
resource_value = resource_object[k]
if v != resource_value:
objects_differ = '{0} {1} {2}'.format(k, v, resource_value)
break
if objects_differ:
return state_data
else:
return {} | python | def _diff(state_data, resource_object):
'''helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update.
'''
objects_differ = None
for k, v in state_data['service'].items():
if k == 'escalation_policy_id':
resource_value = resource_object['escalation_policy']['id']
elif k == 'service_key':
# service_key on create must 'foo' but the GET will return 'foo@bar.pagerduty.com'
resource_value = resource_object['service_key']
if '@' in resource_value:
resource_value = resource_value[0:resource_value.find('@')]
else:
resource_value = resource_object[k]
if v != resource_value:
objects_differ = '{0} {1} {2}'.format(k, v, resource_value)
break
if objects_differ:
return state_data
else:
return {} | [
"def",
"_diff",
"(",
"state_data",
",",
"resource_object",
")",
":",
"objects_differ",
"=",
"None",
"for",
"k",
",",
"v",
"in",
"state_data",
"[",
"'service'",
"]",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'escalation_policy_id'",
":",
"resource_valu... | helper method to compare salt state info with the PagerDuty API json structure,
and determine if we need to update.
returns the dict to pass to the PD API to perform the update, or empty dict if no update. | [
"helper",
"method",
"to",
"compare",
"salt",
"state",
"info",
"with",
"the",
"PagerDuty",
"API",
"json",
"structure",
"and",
"determine",
"if",
"we",
"need",
"to",
"update",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/pagerduty_service.py#L101-L126 | train |
saltstack/salt | salt/modules/baredoc.py | modules_and_args | def modules_and_args(modules=True, states=False, names_only=False):
'''
Walk the Salt install tree and return a dictionary or a list
of the functions therein as well as their arguments.
:param modules: Walk the modules directory if True
:param states: Walk the states directory if True
:param names_only: Return only a list of the callable functions instead of a dictionary with arguments
:return: An OrderedDict with callable function names as keys and lists of arguments as
values (if ``names_only``==False) or simply an ordered list of callable
function nanes (if ``names_only``==True).
CLI Example:
(example truncated for brevity)
.. code-block:: bash
salt myminion baredoc.modules_and_args
myminion:
----------
[...]
at.atrm:
at.jobcheck:
at.mod_watch:
- name
at.present:
- unique_tag
- name
- timespec
- job
- tag
- user
at.watch:
- unique_tag
- name
- timespec
- job
- tag
- user
[...]
'''
dirs = []
module_dir = os.path.dirname(os.path.realpath(__file__))
state_dir = os.path.join(os.path.dirname(module_dir), 'states')
if modules:
dirs.append(module_dir)
if states:
dirs.append(state_dir)
ret = _mods_with_args(dirs)
if names_only:
return sorted(ret.keys())
else:
return OrderedDict(sorted(ret.items())) | python | def modules_and_args(modules=True, states=False, names_only=False):
'''
Walk the Salt install tree and return a dictionary or a list
of the functions therein as well as their arguments.
:param modules: Walk the modules directory if True
:param states: Walk the states directory if True
:param names_only: Return only a list of the callable functions instead of a dictionary with arguments
:return: An OrderedDict with callable function names as keys and lists of arguments as
values (if ``names_only``==False) or simply an ordered list of callable
function nanes (if ``names_only``==True).
CLI Example:
(example truncated for brevity)
.. code-block:: bash
salt myminion baredoc.modules_and_args
myminion:
----------
[...]
at.atrm:
at.jobcheck:
at.mod_watch:
- name
at.present:
- unique_tag
- name
- timespec
- job
- tag
- user
at.watch:
- unique_tag
- name
- timespec
- job
- tag
- user
[...]
'''
dirs = []
module_dir = os.path.dirname(os.path.realpath(__file__))
state_dir = os.path.join(os.path.dirname(module_dir), 'states')
if modules:
dirs.append(module_dir)
if states:
dirs.append(state_dir)
ret = _mods_with_args(dirs)
if names_only:
return sorted(ret.keys())
else:
return OrderedDict(sorted(ret.items())) | [
"def",
"modules_and_args",
"(",
"modules",
"=",
"True",
",",
"states",
"=",
"False",
",",
"names_only",
"=",
"False",
")",
":",
"dirs",
"=",
"[",
"]",
"module_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",... | Walk the Salt install tree and return a dictionary or a list
of the functions therein as well as their arguments.
:param modules: Walk the modules directory if True
:param states: Walk the states directory if True
:param names_only: Return only a list of the callable functions instead of a dictionary with arguments
:return: An OrderedDict with callable function names as keys and lists of arguments as
values (if ``names_only``==False) or simply an ordered list of callable
function nanes (if ``names_only``==True).
CLI Example:
(example truncated for brevity)
.. code-block:: bash
salt myminion baredoc.modules_and_args
myminion:
----------
[...]
at.atrm:
at.jobcheck:
at.mod_watch:
- name
at.present:
- unique_tag
- name
- timespec
- job
- tag
- user
at.watch:
- unique_tag
- name
- timespec
- job
- tag
- user
[...] | [
"Walk",
"the",
"Salt",
"install",
"tree",
"and",
"return",
"a",
"dictionary",
"or",
"a",
"list",
"of",
"the",
"functions",
"therein",
"as",
"well",
"as",
"their",
"arguments",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/baredoc.py#L96-L151 | train |
saltstack/salt | salt/output/pony.py | output | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Mane function
'''
high_out = __salt__['highstate'](data)
return subprocess.check_output(['ponysay', salt.utils.data.decode(high_out)]) | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Mane function
'''
high_out = __salt__['highstate'](data)
return subprocess.check_output(['ponysay', salt.utils.data.decode(high_out)]) | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"high_out",
"=",
"__salt__",
"[",
"'highstate'",
"]",
"(",
"data",
")",
"return",
"subprocess",
".",
"check_output",
"(",
"[",
"'ponysay'",
",",
"salt",
"."... | Mane function | [
"Mane",
"function"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/pony.py#L62-L67 | train |
saltstack/salt | salt/modules/win_dsc.py | run_config | def run_config(path,
source=None,
config_name=None,
config_data=None,
config_data_source=None,
script_parameters=None,
salt_env='base'):
r'''
Compile a DSC Configuration in the form of a PowerShell script (.ps1) and
apply it. The PowerShell script can be cached from the master using the
``source`` option. If there is more than one config within the PowerShell
script, the desired configuration can be applied by passing the name in the
``config`` option.
This command would be the equivalent of running ``dsc.compile_config``
followed by ``dsc.apply_config``.
Args:
path (str): The local path to the PowerShell script that contains the
DSC Configuration. Required.
source (str): The path to the script on ``file_roots`` to cache at the
location specified by ``path``. The source file will be cached
locally and then executed. If source is not passed, the config
script located at ``path`` will be compiled. Optional.
config_name (str): The name of the Configuration within the script to
apply. If the script contains multiple configurations within the
file a ``config_name`` must be specified. If the ``config_name`` is
not specified, the name of the file will be used as the
``config_name`` to run. Optional.
config_data (str): Configuration data in the form of a hash table that
will be passed to the ``ConfigurationData`` parameter when the
``config_name`` is compiled. This can be the path to a ``.psd1``
file containing the proper hash table or the PowerShell code to
create the hash table.
.. versionadded:: 2017.7.0
config_data_source (str): The path to the ``.psd1`` file on
``file_roots`` to cache at the location specified by
``config_data``. If this is specified, ``config_data`` must be a
local path instead of a hash table.
.. versionadded:: 2017.7.0
script_parameters (str): Any additional parameters expected by the
configuration script. These must be defined in the script itself.
.. versionadded:: 2017.7.0
salt_env (str): The salt environment to use when copying the source.
Default is 'base'
Returns:
bool: True if successfully compiled and applied, otherwise False
CLI Example:
To compile a config from a script that already exists on the system:
.. code-block:: bash
salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1
To cache a config script to the system from the master and compile it:
.. code-block:: bash
salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1
'''
ret = compile_config(path=path,
source=source,
config_name=config_name,
config_data=config_data,
config_data_source=config_data_source,
script_parameters=script_parameters,
salt_env=salt_env)
if ret.get('Exists'):
config_path = os.path.dirname(ret['FullName'])
return apply_config(config_path)
else:
return False | python | def run_config(path,
source=None,
config_name=None,
config_data=None,
config_data_source=None,
script_parameters=None,
salt_env='base'):
r'''
Compile a DSC Configuration in the form of a PowerShell script (.ps1) and
apply it. The PowerShell script can be cached from the master using the
``source`` option. If there is more than one config within the PowerShell
script, the desired configuration can be applied by passing the name in the
``config`` option.
This command would be the equivalent of running ``dsc.compile_config``
followed by ``dsc.apply_config``.
Args:
path (str): The local path to the PowerShell script that contains the
DSC Configuration. Required.
source (str): The path to the script on ``file_roots`` to cache at the
location specified by ``path``. The source file will be cached
locally and then executed. If source is not passed, the config
script located at ``path`` will be compiled. Optional.
config_name (str): The name of the Configuration within the script to
apply. If the script contains multiple configurations within the
file a ``config_name`` must be specified. If the ``config_name`` is
not specified, the name of the file will be used as the
``config_name`` to run. Optional.
config_data (str): Configuration data in the form of a hash table that
will be passed to the ``ConfigurationData`` parameter when the
``config_name`` is compiled. This can be the path to a ``.psd1``
file containing the proper hash table or the PowerShell code to
create the hash table.
.. versionadded:: 2017.7.0
config_data_source (str): The path to the ``.psd1`` file on
``file_roots`` to cache at the location specified by
``config_data``. If this is specified, ``config_data`` must be a
local path instead of a hash table.
.. versionadded:: 2017.7.0
script_parameters (str): Any additional parameters expected by the
configuration script. These must be defined in the script itself.
.. versionadded:: 2017.7.0
salt_env (str): The salt environment to use when copying the source.
Default is 'base'
Returns:
bool: True if successfully compiled and applied, otherwise False
CLI Example:
To compile a config from a script that already exists on the system:
.. code-block:: bash
salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1
To cache a config script to the system from the master and compile it:
.. code-block:: bash
salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1
'''
ret = compile_config(path=path,
source=source,
config_name=config_name,
config_data=config_data,
config_data_source=config_data_source,
script_parameters=script_parameters,
salt_env=salt_env)
if ret.get('Exists'):
config_path = os.path.dirname(ret['FullName'])
return apply_config(config_path)
else:
return False | [
"def",
"run_config",
"(",
"path",
",",
"source",
"=",
"None",
",",
"config_name",
"=",
"None",
",",
"config_data",
"=",
"None",
",",
"config_data_source",
"=",
"None",
",",
"script_parameters",
"=",
"None",
",",
"salt_env",
"=",
"'base'",
")",
":",
"ret",
... | r'''
Compile a DSC Configuration in the form of a PowerShell script (.ps1) and
apply it. The PowerShell script can be cached from the master using the
``source`` option. If there is more than one config within the PowerShell
script, the desired configuration can be applied by passing the name in the
``config`` option.
This command would be the equivalent of running ``dsc.compile_config``
followed by ``dsc.apply_config``.
Args:
path (str): The local path to the PowerShell script that contains the
DSC Configuration. Required.
source (str): The path to the script on ``file_roots`` to cache at the
location specified by ``path``. The source file will be cached
locally and then executed. If source is not passed, the config
script located at ``path`` will be compiled. Optional.
config_name (str): The name of the Configuration within the script to
apply. If the script contains multiple configurations within the
file a ``config_name`` must be specified. If the ``config_name`` is
not specified, the name of the file will be used as the
``config_name`` to run. Optional.
config_data (str): Configuration data in the form of a hash table that
will be passed to the ``ConfigurationData`` parameter when the
``config_name`` is compiled. This can be the path to a ``.psd1``
file containing the proper hash table or the PowerShell code to
create the hash table.
.. versionadded:: 2017.7.0
config_data_source (str): The path to the ``.psd1`` file on
``file_roots`` to cache at the location specified by
``config_data``. If this is specified, ``config_data`` must be a
local path instead of a hash table.
.. versionadded:: 2017.7.0
script_parameters (str): Any additional parameters expected by the
configuration script. These must be defined in the script itself.
.. versionadded:: 2017.7.0
salt_env (str): The salt environment to use when copying the source.
Default is 'base'
Returns:
bool: True if successfully compiled and applied, otherwise False
CLI Example:
To compile a config from a script that already exists on the system:
.. code-block:: bash
salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1
To cache a config script to the system from the master and compile it:
.. code-block:: bash
salt '*' dsc.run_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1 | [
"r",
"Compile",
"a",
"DSC",
"Configuration",
"in",
"the",
"form",
"of",
"a",
"PowerShell",
"script",
"(",
".",
"ps1",
")",
"and",
"apply",
"it",
".",
"The",
"PowerShell",
"script",
"can",
"be",
"cached",
"from",
"the",
"master",
"using",
"the",
"source",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L95-L180 | train |
saltstack/salt | salt/modules/win_dsc.py | compile_config | def compile_config(path,
source=None,
config_name=None,
config_data=None,
config_data_source=None,
script_parameters=None,
salt_env='base'):
r'''
Compile a config from a PowerShell script (``.ps1``)
Args:
path (str): Path (local) to the script that will create the ``.mof``
configuration file. If no source is passed, the file must exist
locally. Required.
source (str): Path to the script on ``file_roots`` to cache at the
location specified by ``path``. The source file will be cached
locally and then executed. If source is not passed, the config
script located at ``path`` will be compiled. Optional.
config_name (str): The name of the Configuration within the script to
apply. If the script contains multiple configurations within the
file a ``config_name`` must be specified. If the ``config_name`` is
not specified, the name of the file will be used as the
``config_name`` to run. Optional.
config_data (str): Configuration data in the form of a hash table that
will be passed to the ``ConfigurationData`` parameter when the
``config_name`` is compiled. This can be the path to a ``.psd1``
file containing the proper hash table or the PowerShell code to
create the hash table.
.. versionadded:: 2017.7.0
config_data_source (str): The path to the ``.psd1`` file on
``file_roots`` to cache at the location specified by
``config_data``. If this is specified, ``config_data`` must be a
local path instead of a hash table.
.. versionadded:: 2017.7.0
script_parameters (str): Any additional parameters expected by the
configuration script. These must be defined in the script itself.
.. versionadded:: 2017.7.0
salt_env (str): The salt environment to use when copying the source.
Default is 'base'
Returns:
dict: A dictionary containing the results of the compilation
CLI Example:
To compile a config from a script that already exists on the system:
.. code-block:: bash
salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1
To cache a config script to the system from the master and compile it:
.. code-block:: bash
salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1
'''
if source:
log.info('DSC: Caching %s', source)
cached_files = __salt__['cp.get_file'](path=source,
dest=path,
saltenv=salt_env,
makedirs=True)
if not cached_files:
error = 'Failed to cache {0}'.format(source)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
if config_data_source:
log.info('DSC: Caching %s', config_data_source)
cached_files = __salt__['cp.get_file'](path=config_data_source,
dest=config_data,
saltenv=salt_env,
makedirs=True)
if not cached_files:
error = 'Failed to cache {0}'.format(config_data_source)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
# Make sure the path exists
if not os.path.exists(path):
error = '"{0}" not found'.format(path)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
if config_name is None:
# If the name of the config isn't passed, make it the name of the .ps1
config_name = os.path.splitext(os.path.basename(path))[0]
cwd = os.path.dirname(path)
# Run the script and see if the compile command is in the script
cmd = [path]
# Add any script parameters
if script_parameters:
cmd.append(script_parameters)
# Select fields to return
cmd.append('| Select-Object -Property FullName, Extension, Exists, '
'@{Name="LastWriteTime";Expression={Get-Date ($_.LastWriteTime) '
'-Format g}}')
cmd = ' '.join(cmd)
ret = _pshell(cmd, cwd)
if ret:
# Script compiled, return results
if ret.get('Exists'):
log.info('DSC: Compile Config: %s', ret)
return ret
# If you get to this point, the script did not contain a compile command
# dot source the script to compile the state and generate the mof file
cmd = ['.', path]
if script_parameters:
cmd.append(script_parameters)
cmd.extend([';', config_name])
if config_data:
cmd.append(config_data)
cmd.append('| Select-Object -Property FullName, Extension, Exists, '
'@{Name="LastWriteTime";Expression={Get-Date ($_.LastWriteTime) '
'-Format g}}')
cmd = ' '.join(cmd)
ret = _pshell(cmd, cwd)
if ret:
# Script compiled, return results
if ret.get('Exists'):
log.info('DSC: Compile Config: %s', ret)
return ret
error = 'Failed to compile config: {0}'.format(path)
error += '\nReturned: {0}'.format(ret)
log.error('DSC: %s', error)
raise CommandExecutionError(error) | python | def compile_config(path,
source=None,
config_name=None,
config_data=None,
config_data_source=None,
script_parameters=None,
salt_env='base'):
r'''
Compile a config from a PowerShell script (``.ps1``)
Args:
path (str): Path (local) to the script that will create the ``.mof``
configuration file. If no source is passed, the file must exist
locally. Required.
source (str): Path to the script on ``file_roots`` to cache at the
location specified by ``path``. The source file will be cached
locally and then executed. If source is not passed, the config
script located at ``path`` will be compiled. Optional.
config_name (str): The name of the Configuration within the script to
apply. If the script contains multiple configurations within the
file a ``config_name`` must be specified. If the ``config_name`` is
not specified, the name of the file will be used as the
``config_name`` to run. Optional.
config_data (str): Configuration data in the form of a hash table that
will be passed to the ``ConfigurationData`` parameter when the
``config_name`` is compiled. This can be the path to a ``.psd1``
file containing the proper hash table or the PowerShell code to
create the hash table.
.. versionadded:: 2017.7.0
config_data_source (str): The path to the ``.psd1`` file on
``file_roots`` to cache at the location specified by
``config_data``. If this is specified, ``config_data`` must be a
local path instead of a hash table.
.. versionadded:: 2017.7.0
script_parameters (str): Any additional parameters expected by the
configuration script. These must be defined in the script itself.
.. versionadded:: 2017.7.0
salt_env (str): The salt environment to use when copying the source.
Default is 'base'
Returns:
dict: A dictionary containing the results of the compilation
CLI Example:
To compile a config from a script that already exists on the system:
.. code-block:: bash
salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1
To cache a config script to the system from the master and compile it:
.. code-block:: bash
salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1
'''
if source:
log.info('DSC: Caching %s', source)
cached_files = __salt__['cp.get_file'](path=source,
dest=path,
saltenv=salt_env,
makedirs=True)
if not cached_files:
error = 'Failed to cache {0}'.format(source)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
if config_data_source:
log.info('DSC: Caching %s', config_data_source)
cached_files = __salt__['cp.get_file'](path=config_data_source,
dest=config_data,
saltenv=salt_env,
makedirs=True)
if not cached_files:
error = 'Failed to cache {0}'.format(config_data_source)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
# Make sure the path exists
if not os.path.exists(path):
error = '"{0}" not found'.format(path)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
if config_name is None:
# If the name of the config isn't passed, make it the name of the .ps1
config_name = os.path.splitext(os.path.basename(path))[0]
cwd = os.path.dirname(path)
# Run the script and see if the compile command is in the script
cmd = [path]
# Add any script parameters
if script_parameters:
cmd.append(script_parameters)
# Select fields to return
cmd.append('| Select-Object -Property FullName, Extension, Exists, '
'@{Name="LastWriteTime";Expression={Get-Date ($_.LastWriteTime) '
'-Format g}}')
cmd = ' '.join(cmd)
ret = _pshell(cmd, cwd)
if ret:
# Script compiled, return results
if ret.get('Exists'):
log.info('DSC: Compile Config: %s', ret)
return ret
# If you get to this point, the script did not contain a compile command
# dot source the script to compile the state and generate the mof file
cmd = ['.', path]
if script_parameters:
cmd.append(script_parameters)
cmd.extend([';', config_name])
if config_data:
cmd.append(config_data)
cmd.append('| Select-Object -Property FullName, Extension, Exists, '
'@{Name="LastWriteTime";Expression={Get-Date ($_.LastWriteTime) '
'-Format g}}')
cmd = ' '.join(cmd)
ret = _pshell(cmd, cwd)
if ret:
# Script compiled, return results
if ret.get('Exists'):
log.info('DSC: Compile Config: %s', ret)
return ret
error = 'Failed to compile config: {0}'.format(path)
error += '\nReturned: {0}'.format(ret)
log.error('DSC: %s', error)
raise CommandExecutionError(error) | [
"def",
"compile_config",
"(",
"path",
",",
"source",
"=",
"None",
",",
"config_name",
"=",
"None",
",",
"config_data",
"=",
"None",
",",
"config_data_source",
"=",
"None",
",",
"script_parameters",
"=",
"None",
",",
"salt_env",
"=",
"'base'",
")",
":",
"if... | r'''
Compile a config from a PowerShell script (``.ps1``)
Args:
path (str): Path (local) to the script that will create the ``.mof``
configuration file. If no source is passed, the file must exist
locally. Required.
source (str): Path to the script on ``file_roots`` to cache at the
location specified by ``path``. The source file will be cached
locally and then executed. If source is not passed, the config
script located at ``path`` will be compiled. Optional.
config_name (str): The name of the Configuration within the script to
apply. If the script contains multiple configurations within the
file a ``config_name`` must be specified. If the ``config_name`` is
not specified, the name of the file will be used as the
``config_name`` to run. Optional.
config_data (str): Configuration data in the form of a hash table that
will be passed to the ``ConfigurationData`` parameter when the
``config_name`` is compiled. This can be the path to a ``.psd1``
file containing the proper hash table or the PowerShell code to
create the hash table.
.. versionadded:: 2017.7.0
config_data_source (str): The path to the ``.psd1`` file on
``file_roots`` to cache at the location specified by
``config_data``. If this is specified, ``config_data`` must be a
local path instead of a hash table.
.. versionadded:: 2017.7.0
script_parameters (str): Any additional parameters expected by the
configuration script. These must be defined in the script itself.
.. versionadded:: 2017.7.0
salt_env (str): The salt environment to use when copying the source.
Default is 'base'
Returns:
dict: A dictionary containing the results of the compilation
CLI Example:
To compile a config from a script that already exists on the system:
.. code-block:: bash
salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1
To cache a config script to the system from the master and compile it:
.. code-block:: bash
salt '*' dsc.compile_config C:\\DSC\\WebsiteConfig.ps1 salt://dsc/configs/WebsiteConfig.ps1 | [
"r",
"Compile",
"a",
"config",
"from",
"a",
"PowerShell",
"script",
"(",
".",
"ps1",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L183-L329 | train |
saltstack/salt | salt/modules/win_dsc.py | apply_config | def apply_config(path, source=None, salt_env='base'):
r'''
Run an compiled DSC configuration (a folder containing a .mof file). The
folder can be cached from the salt master using the ``source`` option.
Args:
path (str): Local path to the directory that contains the .mof
configuration file to apply. Required.
source (str): Path to the directory that contains the .mof file on the
``file_roots``. The source directory will be copied to the path
directory and then executed. If the path and source directories
differ, the source directory will be applied. If source is not
passed, the config located at ``path`` will be applied. Optional.
salt_env (str): The salt environment to use when copying your source.
Default is 'base'
Returns:
bool: True if successful, otherwise False
CLI Example:
To apply a config that already exists on the the system
.. code-block:: bash
salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration
To cache a configuration from the master and apply it:
.. code-block:: bash
salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration salt://dsc/configs/WebSiteConfiguration
'''
# If you're getting an error along the lines of "The client cannot connect
# to the destination specified in the request.", try the following:
# Enable-PSRemoting -SkipNetworkProfileCheck
config = path
if source:
# Make sure the folder names match
path_name = os.path.basename(os.path.normpath(path))
source_name = os.path.basename(os.path.normpath(source))
if path_name.lower() != source_name.lower():
# Append the Source name to the Path
path = '{0}\\{1}'.format(path, source_name)
log.debug('DSC: %s appended to the path.', source_name)
# Destination path minus the basename
dest_path = os.path.dirname(os.path.normpath(path))
log.info('DSC: Caching %s', source)
cached_files = __salt__['cp.get_dir'](source, dest_path, salt_env)
if not cached_files:
error = 'Failed to copy {0}'.format(source)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
else:
config = os.path.dirname(cached_files[0])
# Make sure the path exists
if not os.path.exists(config):
error = '{0} not found'.format(config)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
# Run the DSC Configuration
# Putting quotes around the parameter protects against command injection
cmd = 'Start-DscConfiguration -Path "{0}" -Wait -Force'.format(config)
_pshell(cmd)
cmd = '$status = Get-DscConfigurationStatus; $status.Status'
ret = _pshell(cmd)
log.info('DSC: Apply Config: %s', ret)
return ret == 'Success' or ret == {} | python | def apply_config(path, source=None, salt_env='base'):
r'''
Run an compiled DSC configuration (a folder containing a .mof file). The
folder can be cached from the salt master using the ``source`` option.
Args:
path (str): Local path to the directory that contains the .mof
configuration file to apply. Required.
source (str): Path to the directory that contains the .mof file on the
``file_roots``. The source directory will be copied to the path
directory and then executed. If the path and source directories
differ, the source directory will be applied. If source is not
passed, the config located at ``path`` will be applied. Optional.
salt_env (str): The salt environment to use when copying your source.
Default is 'base'
Returns:
bool: True if successful, otherwise False
CLI Example:
To apply a config that already exists on the the system
.. code-block:: bash
salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration
To cache a configuration from the master and apply it:
.. code-block:: bash
salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration salt://dsc/configs/WebSiteConfiguration
'''
# If you're getting an error along the lines of "The client cannot connect
# to the destination specified in the request.", try the following:
# Enable-PSRemoting -SkipNetworkProfileCheck
config = path
if source:
# Make sure the folder names match
path_name = os.path.basename(os.path.normpath(path))
source_name = os.path.basename(os.path.normpath(source))
if path_name.lower() != source_name.lower():
# Append the Source name to the Path
path = '{0}\\{1}'.format(path, source_name)
log.debug('DSC: %s appended to the path.', source_name)
# Destination path minus the basename
dest_path = os.path.dirname(os.path.normpath(path))
log.info('DSC: Caching %s', source)
cached_files = __salt__['cp.get_dir'](source, dest_path, salt_env)
if not cached_files:
error = 'Failed to copy {0}'.format(source)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
else:
config = os.path.dirname(cached_files[0])
# Make sure the path exists
if not os.path.exists(config):
error = '{0} not found'.format(config)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
# Run the DSC Configuration
# Putting quotes around the parameter protects against command injection
cmd = 'Start-DscConfiguration -Path "{0}" -Wait -Force'.format(config)
_pshell(cmd)
cmd = '$status = Get-DscConfigurationStatus; $status.Status'
ret = _pshell(cmd)
log.info('DSC: Apply Config: %s', ret)
return ret == 'Success' or ret == {} | [
"def",
"apply_config",
"(",
"path",
",",
"source",
"=",
"None",
",",
"salt_env",
"=",
"'base'",
")",
":",
"# If you're getting an error along the lines of \"The client cannot connect",
"# to the destination specified in the request.\", try the following:",
"# Enable-PSRemoting -SkipN... | r'''
Run an compiled DSC configuration (a folder containing a .mof file). The
folder can be cached from the salt master using the ``source`` option.
Args:
path (str): Local path to the directory that contains the .mof
configuration file to apply. Required.
source (str): Path to the directory that contains the .mof file on the
``file_roots``. The source directory will be copied to the path
directory and then executed. If the path and source directories
differ, the source directory will be applied. If source is not
passed, the config located at ``path`` will be applied. Optional.
salt_env (str): The salt environment to use when copying your source.
Default is 'base'
Returns:
bool: True if successful, otherwise False
CLI Example:
To apply a config that already exists on the the system
.. code-block:: bash
salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration
To cache a configuration from the master and apply it:
.. code-block:: bash
salt '*' dsc.apply_config C:\\DSC\\WebSiteConfiguration salt://dsc/configs/WebSiteConfiguration | [
"r",
"Run",
"an",
"compiled",
"DSC",
"configuration",
"(",
"a",
"folder",
"containing",
"a",
".",
"mof",
"file",
")",
".",
"The",
"folder",
"can",
"be",
"cached",
"from",
"the",
"salt",
"master",
"using",
"the",
"source",
"option",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L332-L408 | train |
saltstack/salt | salt/modules/win_dsc.py | get_config | def get_config():
'''
Get the current DSC Configuration
Returns:
dict: A dictionary representing the DSC Configuration on the machine
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config
'''
cmd = 'Get-DscConfiguration | Select-Object * -ExcludeProperty Cim*'
try:
raw_config = _pshell(cmd, ignore_retcode=True)
except CommandExecutionError as exc:
if 'Current configuration does not exist' in exc.info['stderr']:
raise CommandExecutionError('Not Configured')
raise
config = dict()
if raw_config:
# Get DSC Configuration Name
if 'ConfigurationName' in raw_config[0]:
config[raw_config[0]['ConfigurationName']] = {}
# Add all DSC Configurations by ResourceId
for item in raw_config:
config[item['ConfigurationName']][item['ResourceId']] = {}
for key in item:
if key not in ['ConfigurationName', 'ResourceId']:
config[item['ConfigurationName']][item['ResourceId']][key] = item[key]
return config | python | def get_config():
'''
Get the current DSC Configuration
Returns:
dict: A dictionary representing the DSC Configuration on the machine
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config
'''
cmd = 'Get-DscConfiguration | Select-Object * -ExcludeProperty Cim*'
try:
raw_config = _pshell(cmd, ignore_retcode=True)
except CommandExecutionError as exc:
if 'Current configuration does not exist' in exc.info['stderr']:
raise CommandExecutionError('Not Configured')
raise
config = dict()
if raw_config:
# Get DSC Configuration Name
if 'ConfigurationName' in raw_config[0]:
config[raw_config[0]['ConfigurationName']] = {}
# Add all DSC Configurations by ResourceId
for item in raw_config:
config[item['ConfigurationName']][item['ResourceId']] = {}
for key in item:
if key not in ['ConfigurationName', 'ResourceId']:
config[item['ConfigurationName']][item['ResourceId']][key] = item[key]
return config | [
"def",
"get_config",
"(",
")",
":",
"cmd",
"=",
"'Get-DscConfiguration | Select-Object * -ExcludeProperty Cim*'",
"try",
":",
"raw_config",
"=",
"_pshell",
"(",
"cmd",
",",
"ignore_retcode",
"=",
"True",
")",
"except",
"CommandExecutionError",
"as",
"exc",
":",
"if"... | Get the current DSC Configuration
Returns:
dict: A dictionary representing the DSC Configuration on the machine
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config | [
"Get",
"the",
"current",
"DSC",
"Configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L411-L448 | train |
saltstack/salt | salt/modules/win_dsc.py | remove_config | def remove_config(reset=False):
'''
Remove the current DSC Configuration. Removes current, pending, and previous
dsc configurations.
.. versionadded:: 2017.7.5
Args:
reset (bool):
Attempts to reset the DSC configuration by removing the following
from ``C:\\Windows\\System32\\Configuration``:
- File: DSCStatusHistory.mof
- File: DSCEngineCache.mof
- Dir: ConfigurationStatus
Default is False
.. warning::
``remove_config`` may fail to reset the DSC environment if any
of the files in the ``ConfigurationStatus`` directory. If you
wait a few minutes and run again, it may complete successfully.
Returns:
bool: True if successful
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.remove_config True
'''
# Stopping a running config (not likely to occur)
cmd = 'Stop-DscConfiguration'
log.info('DSC: Stopping Running Configuration')
try:
_pshell(cmd)
except CommandExecutionError as exc:
if exc.info['retcode'] != 0:
raise CommandExecutionError('Failed to Stop DSC Configuration',
info=exc.info)
log.info('DSC: %s', exc.info['stdout'])
# Remove configuration files
cmd = 'Remove-DscConfigurationDocument -Stage Current, Pending, Previous ' \
'-Force'
log.info('DSC: Removing Configuration')
try:
_pshell(cmd)
except CommandExecutionError as exc:
if exc.info['retcode'] != 0:
raise CommandExecutionError('Failed to remove DSC Configuration',
info=exc.info)
log.info('DSC: %s', exc.info['stdout'])
if not reset:
return True
def _remove_fs_obj(path):
if os.path.exists(path):
log.info('DSC: Removing %s', path)
if not __salt__['file.remove'](path):
error = 'Failed to remove {0}'.format(path)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
dsc_config_dir = '{0}\\System32\\Configuration' \
''.format(os.getenv('SystemRoot', 'C:\\Windows'))
# Remove History
_remove_fs_obj('{0}\\DSCStatusHistory.mof'.format(dsc_config_dir))
# Remove Engine Cache
_remove_fs_obj('{0}\\DSCEngineCache.mof'.format(dsc_config_dir))
# Remove Status Directory
_remove_fs_obj('{0}\\ConfigurationStatus'.format(dsc_config_dir))
return True | python | def remove_config(reset=False):
'''
Remove the current DSC Configuration. Removes current, pending, and previous
dsc configurations.
.. versionadded:: 2017.7.5
Args:
reset (bool):
Attempts to reset the DSC configuration by removing the following
from ``C:\\Windows\\System32\\Configuration``:
- File: DSCStatusHistory.mof
- File: DSCEngineCache.mof
- Dir: ConfigurationStatus
Default is False
.. warning::
``remove_config`` may fail to reset the DSC environment if any
of the files in the ``ConfigurationStatus`` directory. If you
wait a few minutes and run again, it may complete successfully.
Returns:
bool: True if successful
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.remove_config True
'''
# Stopping a running config (not likely to occur)
cmd = 'Stop-DscConfiguration'
log.info('DSC: Stopping Running Configuration')
try:
_pshell(cmd)
except CommandExecutionError as exc:
if exc.info['retcode'] != 0:
raise CommandExecutionError('Failed to Stop DSC Configuration',
info=exc.info)
log.info('DSC: %s', exc.info['stdout'])
# Remove configuration files
cmd = 'Remove-DscConfigurationDocument -Stage Current, Pending, Previous ' \
'-Force'
log.info('DSC: Removing Configuration')
try:
_pshell(cmd)
except CommandExecutionError as exc:
if exc.info['retcode'] != 0:
raise CommandExecutionError('Failed to remove DSC Configuration',
info=exc.info)
log.info('DSC: %s', exc.info['stdout'])
if not reset:
return True
def _remove_fs_obj(path):
if os.path.exists(path):
log.info('DSC: Removing %s', path)
if not __salt__['file.remove'](path):
error = 'Failed to remove {0}'.format(path)
log.error('DSC: %s', error)
raise CommandExecutionError(error)
dsc_config_dir = '{0}\\System32\\Configuration' \
''.format(os.getenv('SystemRoot', 'C:\\Windows'))
# Remove History
_remove_fs_obj('{0}\\DSCStatusHistory.mof'.format(dsc_config_dir))
# Remove Engine Cache
_remove_fs_obj('{0}\\DSCEngineCache.mof'.format(dsc_config_dir))
# Remove Status Directory
_remove_fs_obj('{0}\\ConfigurationStatus'.format(dsc_config_dir))
return True | [
"def",
"remove_config",
"(",
"reset",
"=",
"False",
")",
":",
"# Stopping a running config (not likely to occur)",
"cmd",
"=",
"'Stop-DscConfiguration'",
"log",
".",
"info",
"(",
"'DSC: Stopping Running Configuration'",
")",
"try",
":",
"_pshell",
"(",
"cmd",
")",
"ex... | Remove the current DSC Configuration. Removes current, pending, and previous
dsc configurations.
.. versionadded:: 2017.7.5
Args:
reset (bool):
Attempts to reset the DSC configuration by removing the following
from ``C:\\Windows\\System32\\Configuration``:
- File: DSCStatusHistory.mof
- File: DSCEngineCache.mof
- Dir: ConfigurationStatus
Default is False
.. warning::
``remove_config`` may fail to reset the DSC environment if any
of the files in the ``ConfigurationStatus`` directory. If you
wait a few minutes and run again, it may complete successfully.
Returns:
bool: True if successful
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.remove_config True | [
"Remove",
"the",
"current",
"DSC",
"Configuration",
".",
"Removes",
"current",
"pending",
"and",
"previous",
"dsc",
"configurations",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L451-L532 | train |
saltstack/salt | salt/modules/win_dsc.py | restore_config | def restore_config():
'''
Reapplies the previous configuration.
.. versionadded:: 2017.7.5
.. note::
The current configuration will be come the previous configuration. If
run a second time back-to-back it is like toggling between two configs.
Returns:
bool: True if successfully restored
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.restore_config
'''
cmd = 'Restore-DscConfiguration'
try:
_pshell(cmd, ignore_retcode=True)
except CommandExecutionError as exc:
if 'A previous configuration does not exist' in exc.info['stderr']:
raise CommandExecutionError('Previous Configuration Not Found')
raise
return True | python | def restore_config():
'''
Reapplies the previous configuration.
.. versionadded:: 2017.7.5
.. note::
The current configuration will be come the previous configuration. If
run a second time back-to-back it is like toggling between two configs.
Returns:
bool: True if successfully restored
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.restore_config
'''
cmd = 'Restore-DscConfiguration'
try:
_pshell(cmd, ignore_retcode=True)
except CommandExecutionError as exc:
if 'A previous configuration does not exist' in exc.info['stderr']:
raise CommandExecutionError('Previous Configuration Not Found')
raise
return True | [
"def",
"restore_config",
"(",
")",
":",
"cmd",
"=",
"'Restore-DscConfiguration'",
"try",
":",
"_pshell",
"(",
"cmd",
",",
"ignore_retcode",
"=",
"True",
")",
"except",
"CommandExecutionError",
"as",
"exc",
":",
"if",
"'A previous configuration does not exist'",
"in"... | Reapplies the previous configuration.
.. versionadded:: 2017.7.5
.. note::
The current configuration will be come the previous configuration. If
run a second time back-to-back it is like toggling between two configs.
Returns:
bool: True if successfully restored
Raises:
CommandExecutionError: On failure
CLI Example:
.. code-block:: bash
salt '*' dsc.restore_config | [
"Reapplies",
"the",
"previous",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L535-L564 | train |
saltstack/salt | salt/modules/win_dsc.py | get_config_status | def get_config_status():
'''
Get the status of the current DSC Configuration
Returns:
dict: A dictionary representing the status of the current DSC
Configuration on the machine
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config_status
'''
cmd = 'Get-DscConfigurationStatus | ' \
'Select-Object -Property HostName, Status, MetaData, ' \
'@{Name="StartDate";Expression={Get-Date ($_.StartDate) -Format g}}, ' \
'Type, Mode, RebootRequested, NumberofResources'
try:
return _pshell(cmd, ignore_retcode=True)
except CommandExecutionError as exc:
if 'No status information available' in exc.info['stderr']:
raise CommandExecutionError('Not Configured')
raise | python | def get_config_status():
'''
Get the status of the current DSC Configuration
Returns:
dict: A dictionary representing the status of the current DSC
Configuration on the machine
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config_status
'''
cmd = 'Get-DscConfigurationStatus | ' \
'Select-Object -Property HostName, Status, MetaData, ' \
'@{Name="StartDate";Expression={Get-Date ($_.StartDate) -Format g}}, ' \
'Type, Mode, RebootRequested, NumberofResources'
try:
return _pshell(cmd, ignore_retcode=True)
except CommandExecutionError as exc:
if 'No status information available' in exc.info['stderr']:
raise CommandExecutionError('Not Configured')
raise | [
"def",
"get_config_status",
"(",
")",
":",
"cmd",
"=",
"'Get-DscConfigurationStatus | '",
"'Select-Object -Property HostName, Status, MetaData, '",
"'@{Name=\"StartDate\";Expression={Get-Date ($_.StartDate) -Format g}}, '",
"'Type, Mode, RebootRequested, NumberofResources'",
"try",
":",
"r... | Get the status of the current DSC Configuration
Returns:
dict: A dictionary representing the status of the current DSC
Configuration on the machine
CLI Example:
.. code-block:: bash
salt '*' dsc.get_config_status | [
"Get",
"the",
"status",
"of",
"the",
"current",
"DSC",
"Configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L589-L612 | train |
saltstack/salt | salt/modules/win_dsc.py | set_lcm_config | def set_lcm_config(config_mode=None,
config_mode_freq=None,
refresh_freq=None,
reboot_if_needed=None,
action_after_reboot=None,
refresh_mode=None,
certificate_id=None,
configuration_id=None,
allow_module_overwrite=None,
debug_mode=False,
status_retention_days=None):
'''
For detailed descriptions of the parameters see:
https://msdn.microsoft.com/en-us/PowerShell/DSC/metaConfig
config_mode (str): How the LCM applies the configuration. Valid values
are:
- ApplyOnly
- ApplyAndMonitor
- ApplyAndAutoCorrect
config_mode_freq (int): How often, in minutes, the current configuration
is checked and applied. Ignored if config_mode is set to ApplyOnly.
Default is 15.
refresh_mode (str): How the LCM gets configurations. Valid values are:
- Disabled
- Push
- Pull
refresh_freq (int): How often, in minutes, the LCM checks for updated
configurations. (pull mode only) Default is 30.
reboot_if_needed (bool): Reboot the machine if needed after a
configuration is applied. Default is False.
action_after_reboot (str): Action to take after reboot. Valid values
are:
- ContinueConfiguration
- StopConfiguration
certificate_id (guid): A GUID that specifies a certificate used to
access the configuration: (pull mode)
configuration_id (guid): A GUID that identifies the config file to get
from a pull server. (pull mode)
allow_module_overwrite (bool): New configs are allowed to overwrite old
ones on the target node.
debug_mode (str): Sets the debug level. Valid values are:
- None
- ForceModuleImport
- All
status_retention_days (int): Number of days to keep status of the
current config.
.. note::
Either ``config_mode_freq`` or ``refresh_freq`` needs to be a
multiple of the other. See documentation on MSDN for more details.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' dsc.set_lcm_config ApplyOnly
'''
temp_dir = os.getenv('TEMP', '{0}\\temp'.format(os.getenv('WINDIR')))
cmd = 'Configuration SaltConfig {'
cmd += ' Node localhost {'
cmd += ' LocalConfigurationManager {'
if config_mode:
if config_mode not in ('ApplyOnly', 'ApplyAndMonitor',
'ApplyAndAutoCorrect'):
error = 'config_mode must be one of ApplyOnly, ApplyAndMonitor, ' \
'or ApplyAndAutoCorrect. Passed {0}'.format(config_mode)
raise SaltInvocationError(error)
cmd += ' ConfigurationMode = "{0}";'.format(config_mode)
if config_mode_freq:
if not isinstance(config_mode_freq, int):
error = 'config_mode_freq must be an integer. Passed {0}'.format(
config_mode_freq
)
raise SaltInvocationError(error)
cmd += ' ConfigurationModeFrequencyMins = {0};'.format(config_mode_freq)
if refresh_mode:
if refresh_mode not in ('Disabled', 'Push', 'Pull'):
raise SaltInvocationError(
'refresh_mode must be one of Disabled, Push, or Pull'
)
cmd += ' RefreshMode = "{0}";'.format(refresh_mode)
if refresh_freq:
if not isinstance(refresh_freq, int):
raise SaltInvocationError('refresh_freq must be an integer')
cmd += ' RefreshFrequencyMins = {0};'.format(refresh_freq)
if reboot_if_needed is not None:
if not isinstance(reboot_if_needed, bool):
raise SaltInvocationError('reboot_if_needed must be a boolean value')
if reboot_if_needed:
reboot_if_needed = '$true'
else:
reboot_if_needed = '$false'
cmd += ' RebootNodeIfNeeded = {0};'.format(reboot_if_needed)
if action_after_reboot:
if action_after_reboot not in ('ContinueConfiguration',
'StopConfiguration'):
raise SaltInvocationError(
'action_after_reboot must be one of '
'ContinueConfiguration or StopConfiguration'
)
cmd += ' ActionAfterReboot = "{0}"'.format(action_after_reboot)
if certificate_id is not None:
if certificate_id == '':
certificate_id = None
cmd += ' CertificateID = "{0}";'.format(certificate_id)
if configuration_id is not None:
if configuration_id == '':
configuration_id = None
cmd += ' ConfigurationID = "{0}";'.format(configuration_id)
if allow_module_overwrite is not None:
if not isinstance(allow_module_overwrite, bool):
raise SaltInvocationError('allow_module_overwrite must be a boolean value')
if allow_module_overwrite:
allow_module_overwrite = '$true'
else:
allow_module_overwrite = '$false'
cmd += ' AllowModuleOverwrite = {0};'.format(allow_module_overwrite)
if debug_mode is not False:
if debug_mode is None:
debug_mode = 'None'
if debug_mode not in ('None', 'ForceModuleImport', 'All'):
raise SaltInvocationError(
'debug_mode must be one of None, ForceModuleImport, '
'ResourceScriptBreakAll, or All'
)
cmd += ' DebugMode = "{0}";'.format(debug_mode)
if status_retention_days:
if not isinstance(status_retention_days, int):
raise SaltInvocationError('status_retention_days must be an integer')
cmd += ' StatusRetentionTimeInDays = {0};'.format(status_retention_days)
cmd += ' }}};'
cmd += r'SaltConfig -OutputPath "{0}\SaltConfig"'.format(temp_dir)
# Execute Config to create the .mof
_pshell(cmd)
# Apply the config
cmd = r'Set-DscLocalConfigurationManager -Path "{0}\SaltConfig"' \
r''.format(temp_dir)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True)
__salt__['file.remove'](r'{0}\SaltConfig'.format(temp_dir))
if not ret['retcode']:
log.info('DSC: LCM config applied successfully')
return True
else:
log.error('DSC: Failed to apply LCM config. Error %s', ret)
return False | python | def set_lcm_config(config_mode=None,
config_mode_freq=None,
refresh_freq=None,
reboot_if_needed=None,
action_after_reboot=None,
refresh_mode=None,
certificate_id=None,
configuration_id=None,
allow_module_overwrite=None,
debug_mode=False,
status_retention_days=None):
'''
For detailed descriptions of the parameters see:
https://msdn.microsoft.com/en-us/PowerShell/DSC/metaConfig
config_mode (str): How the LCM applies the configuration. Valid values
are:
- ApplyOnly
- ApplyAndMonitor
- ApplyAndAutoCorrect
config_mode_freq (int): How often, in minutes, the current configuration
is checked and applied. Ignored if config_mode is set to ApplyOnly.
Default is 15.
refresh_mode (str): How the LCM gets configurations. Valid values are:
- Disabled
- Push
- Pull
refresh_freq (int): How often, in minutes, the LCM checks for updated
configurations. (pull mode only) Default is 30.
reboot_if_needed (bool): Reboot the machine if needed after a
configuration is applied. Default is False.
action_after_reboot (str): Action to take after reboot. Valid values
are:
- ContinueConfiguration
- StopConfiguration
certificate_id (guid): A GUID that specifies a certificate used to
access the configuration: (pull mode)
configuration_id (guid): A GUID that identifies the config file to get
from a pull server. (pull mode)
allow_module_overwrite (bool): New configs are allowed to overwrite old
ones on the target node.
debug_mode (str): Sets the debug level. Valid values are:
- None
- ForceModuleImport
- All
status_retention_days (int): Number of days to keep status of the
current config.
.. note::
Either ``config_mode_freq`` or ``refresh_freq`` needs to be a
multiple of the other. See documentation on MSDN for more details.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' dsc.set_lcm_config ApplyOnly
'''
temp_dir = os.getenv('TEMP', '{0}\\temp'.format(os.getenv('WINDIR')))
cmd = 'Configuration SaltConfig {'
cmd += ' Node localhost {'
cmd += ' LocalConfigurationManager {'
if config_mode:
if config_mode not in ('ApplyOnly', 'ApplyAndMonitor',
'ApplyAndAutoCorrect'):
error = 'config_mode must be one of ApplyOnly, ApplyAndMonitor, ' \
'or ApplyAndAutoCorrect. Passed {0}'.format(config_mode)
raise SaltInvocationError(error)
cmd += ' ConfigurationMode = "{0}";'.format(config_mode)
if config_mode_freq:
if not isinstance(config_mode_freq, int):
error = 'config_mode_freq must be an integer. Passed {0}'.format(
config_mode_freq
)
raise SaltInvocationError(error)
cmd += ' ConfigurationModeFrequencyMins = {0};'.format(config_mode_freq)
if refresh_mode:
if refresh_mode not in ('Disabled', 'Push', 'Pull'):
raise SaltInvocationError(
'refresh_mode must be one of Disabled, Push, or Pull'
)
cmd += ' RefreshMode = "{0}";'.format(refresh_mode)
if refresh_freq:
if not isinstance(refresh_freq, int):
raise SaltInvocationError('refresh_freq must be an integer')
cmd += ' RefreshFrequencyMins = {0};'.format(refresh_freq)
if reboot_if_needed is not None:
if not isinstance(reboot_if_needed, bool):
raise SaltInvocationError('reboot_if_needed must be a boolean value')
if reboot_if_needed:
reboot_if_needed = '$true'
else:
reboot_if_needed = '$false'
cmd += ' RebootNodeIfNeeded = {0};'.format(reboot_if_needed)
if action_after_reboot:
if action_after_reboot not in ('ContinueConfiguration',
'StopConfiguration'):
raise SaltInvocationError(
'action_after_reboot must be one of '
'ContinueConfiguration or StopConfiguration'
)
cmd += ' ActionAfterReboot = "{0}"'.format(action_after_reboot)
if certificate_id is not None:
if certificate_id == '':
certificate_id = None
cmd += ' CertificateID = "{0}";'.format(certificate_id)
if configuration_id is not None:
if configuration_id == '':
configuration_id = None
cmd += ' ConfigurationID = "{0}";'.format(configuration_id)
if allow_module_overwrite is not None:
if not isinstance(allow_module_overwrite, bool):
raise SaltInvocationError('allow_module_overwrite must be a boolean value')
if allow_module_overwrite:
allow_module_overwrite = '$true'
else:
allow_module_overwrite = '$false'
cmd += ' AllowModuleOverwrite = {0};'.format(allow_module_overwrite)
if debug_mode is not False:
if debug_mode is None:
debug_mode = 'None'
if debug_mode not in ('None', 'ForceModuleImport', 'All'):
raise SaltInvocationError(
'debug_mode must be one of None, ForceModuleImport, '
'ResourceScriptBreakAll, or All'
)
cmd += ' DebugMode = "{0}";'.format(debug_mode)
if status_retention_days:
if not isinstance(status_retention_days, int):
raise SaltInvocationError('status_retention_days must be an integer')
cmd += ' StatusRetentionTimeInDays = {0};'.format(status_retention_days)
cmd += ' }}};'
cmd += r'SaltConfig -OutputPath "{0}\SaltConfig"'.format(temp_dir)
# Execute Config to create the .mof
_pshell(cmd)
# Apply the config
cmd = r'Set-DscLocalConfigurationManager -Path "{0}\SaltConfig"' \
r''.format(temp_dir)
ret = __salt__['cmd.run_all'](cmd, shell='powershell', python_shell=True)
__salt__['file.remove'](r'{0}\SaltConfig'.format(temp_dir))
if not ret['retcode']:
log.info('DSC: LCM config applied successfully')
return True
else:
log.error('DSC: Failed to apply LCM config. Error %s', ret)
return False | [
"def",
"set_lcm_config",
"(",
"config_mode",
"=",
"None",
",",
"config_mode_freq",
"=",
"None",
",",
"refresh_freq",
"=",
"None",
",",
"reboot_if_needed",
"=",
"None",
",",
"action_after_reboot",
"=",
"None",
",",
"refresh_mode",
"=",
"None",
",",
"certificate_i... | For detailed descriptions of the parameters see:
https://msdn.microsoft.com/en-us/PowerShell/DSC/metaConfig
config_mode (str): How the LCM applies the configuration. Valid values
are:
- ApplyOnly
- ApplyAndMonitor
- ApplyAndAutoCorrect
config_mode_freq (int): How often, in minutes, the current configuration
is checked and applied. Ignored if config_mode is set to ApplyOnly.
Default is 15.
refresh_mode (str): How the LCM gets configurations. Valid values are:
- Disabled
- Push
- Pull
refresh_freq (int): How often, in minutes, the LCM checks for updated
configurations. (pull mode only) Default is 30.
reboot_if_needed (bool): Reboot the machine if needed after a
configuration is applied. Default is False.
action_after_reboot (str): Action to take after reboot. Valid values
are:
- ContinueConfiguration
- StopConfiguration
certificate_id (guid): A GUID that specifies a certificate used to
access the configuration: (pull mode)
configuration_id (guid): A GUID that identifies the config file to get
from a pull server. (pull mode)
allow_module_overwrite (bool): New configs are allowed to overwrite old
ones on the target node.
debug_mode (str): Sets the debug level. Valid values are:
- None
- ForceModuleImport
- All
status_retention_days (int): Number of days to keep status of the
current config.
.. note::
Either ``config_mode_freq`` or ``refresh_freq`` needs to be a
multiple of the other. See documentation on MSDN for more details.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' dsc.set_lcm_config ApplyOnly | [
"For",
"detailed",
"descriptions",
"of",
"the",
"parameters",
"see",
":",
"https",
":",
"//",
"msdn",
".",
"microsoft",
".",
"com",
"/",
"en",
"-",
"us",
"/",
"PowerShell",
"/",
"DSC",
"/",
"metaConfig"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_dsc.py#L637-L801 | train |
saltstack/salt | salt/modules/sensors.py | sense | def sense(chip, fahrenheit=False):
'''
Gather lm-sensors data from a given chip
To determine the chip to query, use the 'sensors' command
and see the leading line in the block.
Example:
/usr/bin/sensors
coretemp-isa-0000
Adapter: ISA adapter
Physical id 0: +56.0°C (high = +87.0°C, crit = +105.0°C)
Core 0: +52.0°C (high = +87.0°C, crit = +105.0°C)
Core 1: +50.0°C (high = +87.0°C, crit = +105.0°C)
Core 2: +56.0°C (high = +87.0°C, crit = +105.0°C)
Core 3: +53.0°C (high = +87.0°C, crit = +105.0°C)
Given the above, the chip is 'coretemp-isa-0000'.
'''
extra_args = ''
if fahrenheit is True:
extra_args = '-f'
sensors = __salt__['cmd.run']('/usr/bin/sensors {0} {1}'.format(chip, extra_args), python_shell=False).splitlines()
ret = {}
for sensor in sensors:
sensor_list = sensor.split(':')
if len(sensor_list) >= 2:
ret[sensor_list[0]] = sensor_list[1].lstrip()
return ret | python | def sense(chip, fahrenheit=False):
'''
Gather lm-sensors data from a given chip
To determine the chip to query, use the 'sensors' command
and see the leading line in the block.
Example:
/usr/bin/sensors
coretemp-isa-0000
Adapter: ISA adapter
Physical id 0: +56.0°C (high = +87.0°C, crit = +105.0°C)
Core 0: +52.0°C (high = +87.0°C, crit = +105.0°C)
Core 1: +50.0°C (high = +87.0°C, crit = +105.0°C)
Core 2: +56.0°C (high = +87.0°C, crit = +105.0°C)
Core 3: +53.0°C (high = +87.0°C, crit = +105.0°C)
Given the above, the chip is 'coretemp-isa-0000'.
'''
extra_args = ''
if fahrenheit is True:
extra_args = '-f'
sensors = __salt__['cmd.run']('/usr/bin/sensors {0} {1}'.format(chip, extra_args), python_shell=False).splitlines()
ret = {}
for sensor in sensors:
sensor_list = sensor.split(':')
if len(sensor_list) >= 2:
ret[sensor_list[0]] = sensor_list[1].lstrip()
return ret | [
"def",
"sense",
"(",
"chip",
",",
"fahrenheit",
"=",
"False",
")",
":",
"extra_args",
"=",
"''",
"if",
"fahrenheit",
"is",
"True",
":",
"extra_args",
"=",
"'-f'",
"sensors",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'/usr/bin/sensors {0} {1}'",
".",
"f... | Gather lm-sensors data from a given chip
To determine the chip to query, use the 'sensors' command
and see the leading line in the block.
Example:
/usr/bin/sensors
coretemp-isa-0000
Adapter: ISA adapter
Physical id 0: +56.0°C (high = +87.0°C, crit = +105.0°C)
Core 0: +52.0°C (high = +87.0°C, crit = +105.0°C)
Core 1: +50.0°C (high = +87.0°C, crit = +105.0°C)
Core 2: +56.0°C (high = +87.0°C, crit = +105.0°C)
Core 3: +53.0°C (high = +87.0°C, crit = +105.0°C)
Given the above, the chip is 'coretemp-isa-0000'. | [
"Gather",
"lm",
"-",
"sensors",
"data",
"from",
"a",
"given",
"chip"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sensors.py#L25-L55 | train |
saltstack/salt | salt/states/influxdb_retention_policy.py | convert_duration | def convert_duration(duration):
'''
Convert the a duration string into XXhYYmZZs format
duration
Duration to convert
Returns: duration_string
String representation of duration in XXhYYmZZs format
'''
# durations must be specified in days, weeks or hours
if duration.endswith('h'):
hours = int(duration.split('h'))
elif duration.endswith('d'):
days = duration.split('d')
hours = int(days[0]) * 24
elif duration.endswith('w'):
weeks = duration.split('w')
hours = int(weeks[0]) * 24 * 7
duration_string = str(hours)+'h0m0s'
return duration_string | python | def convert_duration(duration):
'''
Convert the a duration string into XXhYYmZZs format
duration
Duration to convert
Returns: duration_string
String representation of duration in XXhYYmZZs format
'''
# durations must be specified in days, weeks or hours
if duration.endswith('h'):
hours = int(duration.split('h'))
elif duration.endswith('d'):
days = duration.split('d')
hours = int(days[0]) * 24
elif duration.endswith('w'):
weeks = duration.split('w')
hours = int(weeks[0]) * 24 * 7
duration_string = str(hours)+'h0m0s'
return duration_string | [
"def",
"convert_duration",
"(",
"duration",
")",
":",
"# durations must be specified in days, weeks or hours",
"if",
"duration",
".",
"endswith",
"(",
"'h'",
")",
":",
"hours",
"=",
"int",
"(",
"duration",
".",
"split",
"(",
"'h'",
")",
")",
"elif",
"duration",
... | Convert the a duration string into XXhYYmZZs format
duration
Duration to convert
Returns: duration_string
String representation of duration in XXhYYmZZs format | [
"Convert",
"the",
"a",
"duration",
"string",
"into",
"XXhYYmZZs",
"format"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/influxdb_retention_policy.py#L24-L49 | train |
saltstack/salt | salt/states/influxdb_retention_policy.py | present | def present(name, database, duration="7d",
replication=1, default=False,
**client_args):
'''
Ensure that given retention policy is present.
name
Name of the retention policy to create.
database
Database to create retention policy on.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'retention policy {0} is already present'.format(name)}
if not __salt__['influxdb.retention_policy_exists'](name=name,
database=database,
**client_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = ' {0} is absent and will be created'\
.format(name)
return ret
if __salt__['influxdb.create_retention_policy'](
database, name,
duration, replication, default, **client_args
):
ret['comment'] = 'retention policy {0} has been created'\
.format(name)
ret['changes'][name] = 'Present'
return ret
else:
ret['comment'] = 'Failed to create retention policy {0}'\
.format(name)
ret['result'] = False
return ret
else:
current_policy = __salt__['influxdb.get_retention_policy'](database=database, name=name)
update_policy = False
if current_policy['duration'] != convert_duration(duration):
update_policy = True
ret['changes']['duration'] = "Retention changed from {0} to {1}.".format(current_policy['duration'], duration)
if current_policy['replicaN'] != replication:
update_policy = True
ret['changes']['replication'] = "Replication changed from {0} to {1}.".format(current_policy['replicaN'], replication)
if current_policy['default'] != default:
update_policy = True
ret['changes']['default'] = "Default changed from {0} to {1}.".format(current_policy['default'], default)
if update_policy:
if __opts__['test']:
ret['result'] = None
ret['comment'] = ' {0} is present and set to be changed'\
.format(name)
return ret
else:
if __salt__['influxdb.alter_retention_policy'](
database, name,
duration, replication, default, **client_args
):
ret['comment'] = 'retention policy {0} has been changed'\
.format(name)
return ret
else:
ret['comment'] = 'Failed to update retention policy {0}'\
.format(name)
ret['result'] = False
return ret
return ret | python | def present(name, database, duration="7d",
replication=1, default=False,
**client_args):
'''
Ensure that given retention policy is present.
name
Name of the retention policy to create.
database
Database to create retention policy on.
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'retention policy {0} is already present'.format(name)}
if not __salt__['influxdb.retention_policy_exists'](name=name,
database=database,
**client_args):
if __opts__['test']:
ret['result'] = None
ret['comment'] = ' {0} is absent and will be created'\
.format(name)
return ret
if __salt__['influxdb.create_retention_policy'](
database, name,
duration, replication, default, **client_args
):
ret['comment'] = 'retention policy {0} has been created'\
.format(name)
ret['changes'][name] = 'Present'
return ret
else:
ret['comment'] = 'Failed to create retention policy {0}'\
.format(name)
ret['result'] = False
return ret
else:
current_policy = __salt__['influxdb.get_retention_policy'](database=database, name=name)
update_policy = False
if current_policy['duration'] != convert_duration(duration):
update_policy = True
ret['changes']['duration'] = "Retention changed from {0} to {1}.".format(current_policy['duration'], duration)
if current_policy['replicaN'] != replication:
update_policy = True
ret['changes']['replication'] = "Replication changed from {0} to {1}.".format(current_policy['replicaN'], replication)
if current_policy['default'] != default:
update_policy = True
ret['changes']['default'] = "Default changed from {0} to {1}.".format(current_policy['default'], default)
if update_policy:
if __opts__['test']:
ret['result'] = None
ret['comment'] = ' {0} is present and set to be changed'\
.format(name)
return ret
else:
if __salt__['influxdb.alter_retention_policy'](
database, name,
duration, replication, default, **client_args
):
ret['comment'] = 'retention policy {0} has been changed'\
.format(name)
return ret
else:
ret['comment'] = 'Failed to update retention policy {0}'\
.format(name)
ret['result'] = False
return ret
return ret | [
"def",
"present",
"(",
"name",
",",
"database",
",",
"duration",
"=",
"\"7d\"",
",",
"replication",
"=",
"1",
",",
"default",
"=",
"False",
",",
"*",
"*",
"client_args",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
... | Ensure that given retention policy is present.
name
Name of the retention policy to create.
database
Database to create retention policy on. | [
"Ensure",
"that",
"given",
"retention",
"policy",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/influxdb_retention_policy.py#L52-L126 | train |
saltstack/salt | salt/modules/event.py | _dict_subset | def _dict_subset(keys, master_dict):
'''
Return a dictionary of only the subset of keys/values specified in keys
'''
return dict([(k, v) for k, v in six.iteritems(master_dict) if k in keys]) | python | def _dict_subset(keys, master_dict):
'''
Return a dictionary of only the subset of keys/values specified in keys
'''
return dict([(k, v) for k, v in six.iteritems(master_dict) if k in keys]) | [
"def",
"_dict_subset",
"(",
"keys",
",",
"master_dict",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"master_dict",
")",
"if",
"k",
"in",
"keys",
"]",
")"
] | Return a dictionary of only the subset of keys/values specified in keys | [
"Return",
"a",
"dictionary",
"of",
"only",
"the",
"subset",
"of",
"keys",
"/",
"values",
"specified",
"in",
"keys"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/event.py#L27-L31 | train |
saltstack/salt | salt/modules/event.py | fire_master | def fire_master(data, tag, preload=None, timeout=60):
'''
Fire an event off up to the master server
CLI Example:
.. code-block:: bash
salt '*' event.fire_master '{"data":"my event data"}' 'tag'
'''
if (__opts__.get('local', None) or __opts__.get('file_client', None) == 'local') and not __opts__.get('use_master_when_local', False):
# We can't send an event if we're in masterless mode
log.warning('Local mode detected. Event with tag %s will NOT be sent.', tag)
return False
if preload or __opts__.get('__cli') == 'salt-call':
# If preload is specified, we must send a raw event (this is
# slower because it has to independently authenticate)
if 'master_uri' not in __opts__:
__opts__['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(__opts__['interface']),
port=__opts__.get('ret_port', '4506') # TODO, no fallback
)
masters = list()
ret = None
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
auth = salt.crypt.SAuth(__opts__)
load = {'id': __opts__['id'],
'tag': tag,
'data': data,
'tok': auth.gen_token(b'salt'),
'cmd': '_minion_event'}
if isinstance(preload, dict):
load.update(preload)
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
try:
channel.send(load, timeout=timeout)
# channel.send was successful.
# Ensure ret is True.
ret = True
except Exception:
# only set a False ret if it hasn't been sent atleast once
if ret is None:
ret = False
finally:
channel.close()
return ret
else:
# Usually, we can send the event via the minion, which is faster
# because it is already authenticated
try:
me = salt.utils.event.MinionEvent(__opts__, listen=False, keep_loop=True)
return me.fire_event({'data': data, 'tag': tag, 'events': None, 'pretag': None}, 'fire_master')
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
log.debug(lines)
return False | python | def fire_master(data, tag, preload=None, timeout=60):
'''
Fire an event off up to the master server
CLI Example:
.. code-block:: bash
salt '*' event.fire_master '{"data":"my event data"}' 'tag'
'''
if (__opts__.get('local', None) or __opts__.get('file_client', None) == 'local') and not __opts__.get('use_master_when_local', False):
# We can't send an event if we're in masterless mode
log.warning('Local mode detected. Event with tag %s will NOT be sent.', tag)
return False
if preload or __opts__.get('__cli') == 'salt-call':
# If preload is specified, we must send a raw event (this is
# slower because it has to independently authenticate)
if 'master_uri' not in __opts__:
__opts__['master_uri'] = 'tcp://{ip}:{port}'.format(
ip=salt.utils.zeromq.ip_bracket(__opts__['interface']),
port=__opts__.get('ret_port', '4506') # TODO, no fallback
)
masters = list()
ret = None
if 'master_uri_list' in __opts__:
for master_uri in __opts__['master_uri_list']:
masters.append(master_uri)
else:
masters.append(__opts__['master_uri'])
auth = salt.crypt.SAuth(__opts__)
load = {'id': __opts__['id'],
'tag': tag,
'data': data,
'tok': auth.gen_token(b'salt'),
'cmd': '_minion_event'}
if isinstance(preload, dict):
load.update(preload)
for master in masters:
channel = salt.transport.client.ReqChannel.factory(__opts__, master_uri=master)
try:
channel.send(load, timeout=timeout)
# channel.send was successful.
# Ensure ret is True.
ret = True
except Exception:
# only set a False ret if it hasn't been sent atleast once
if ret is None:
ret = False
finally:
channel.close()
return ret
else:
# Usually, we can send the event via the minion, which is faster
# because it is already authenticated
try:
me = salt.utils.event.MinionEvent(__opts__, listen=False, keep_loop=True)
return me.fire_event({'data': data, 'tag': tag, 'events': None, 'pretag': None}, 'fire_master')
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
log.debug(lines)
return False | [
"def",
"fire_master",
"(",
"data",
",",
"tag",
",",
"preload",
"=",
"None",
",",
"timeout",
"=",
"60",
")",
":",
"if",
"(",
"__opts__",
".",
"get",
"(",
"'local'",
",",
"None",
")",
"or",
"__opts__",
".",
"get",
"(",
"'file_client'",
",",
"None",
"... | Fire an event off up to the master server
CLI Example:
.. code-block:: bash
salt '*' event.fire_master '{"data":"my event data"}' 'tag' | [
"Fire",
"an",
"event",
"off",
"up",
"to",
"the",
"master",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/event.py#L34-L98 | train |
saltstack/salt | salt/modules/event.py | fire | def fire(data, tag, timeout=None):
'''
Fire an event on the local minion event bus. Data must be formed as a dict.
CLI Example:
.. code-block:: bash
salt '*' event.fire '{"data":"my event data"}' 'tag'
'''
if timeout is None:
timeout = 60000
else:
timeout = timeout * 1000
try:
event = salt.utils.event.get_event(__opts__.get('__role', 'minion'),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport'],
opts=__opts__,
keep_loop=True,
listen=False)
return event.fire_event(data, tag, timeout=timeout)
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
log.debug(lines)
return False | python | def fire(data, tag, timeout=None):
'''
Fire an event on the local minion event bus. Data must be formed as a dict.
CLI Example:
.. code-block:: bash
salt '*' event.fire '{"data":"my event data"}' 'tag'
'''
if timeout is None:
timeout = 60000
else:
timeout = timeout * 1000
try:
event = salt.utils.event.get_event(__opts__.get('__role', 'minion'),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport'],
opts=__opts__,
keep_loop=True,
listen=False)
return event.fire_event(data, tag, timeout=timeout)
except Exception:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
log.debug(lines)
return False | [
"def",
"fire",
"(",
"data",
",",
"tag",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"None",
":",
"timeout",
"=",
"60000",
"else",
":",
"timeout",
"=",
"timeout",
"*",
"1000",
"try",
":",
"event",
"=",
"salt",
".",
"utils",
".",
... | Fire an event on the local minion event bus. Data must be formed as a dict.
CLI Example:
.. code-block:: bash
salt '*' event.fire '{"data":"my event data"}' 'tag' | [
"Fire",
"an",
"event",
"on",
"the",
"local",
"minion",
"event",
"bus",
".",
"Data",
"must",
"be",
"formed",
"as",
"a",
"dict",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/event.py#L101-L128 | train |
saltstack/salt | salt/modules/event.py | send | def send(tag,
data=None,
preload=None,
with_env=False,
with_grains=False,
with_pillar=False,
with_env_opts=False,
timeout=60,
**kwargs):
'''
Send an event to the Salt Master
.. versionadded:: 2014.7.0
:param tag: A tag to give the event.
Use slashes to create a namespace for related events. E.g.,
``myco/build/buildserver1/start``, ``myco/build/buildserver1/success``,
``myco/build/buildserver1/failure``.
:param data: A dictionary of data to send in the event.
This is free-form. Send any data points that are needed for whoever is
consuming the event. Arguments on the CLI are interpreted as YAML so
complex data structures are possible.
:param with_env: Include environment variables from the current shell
environment in the event data as ``environ``.. This is a short-hand for
working with systems that seed the environment with relevant data such
as Jenkins.
:type with_env: Specify ``True`` to include all environment variables, or
specify a list of strings of variable names to include.
:param with_grains: Include grains from the current minion in the event
data as ``grains``.
:type with_grains: Specify ``True`` to include all grains, or specify a
list of strings of grain names to include.
:param with_pillar: Include Pillar values from the current minion in the
event data as ``pillar``. Remember Pillar data is often sensitive data
so be careful. This is useful for passing ephemeral Pillar values
through an event. Such as passing the ``pillar={}`` kwarg in
:py:func:`state.sls <salt.modules.state.sls>` from the Master, through
an event on the Minion, then back to the Master.
:type with_pillar: Specify ``True`` to include all Pillar values, or
specify a list of strings of Pillar keys to include. It is a
best-practice to only specify a relevant subset of Pillar data.
:param with_env_opts: Include ``saltenv`` and ``pillarenv`` set on minion
at the moment when event is send into event data.
:type with_env_opts: Specify ``True`` to include ``saltenv`` and
``pillarenv`` values or ``False`` to omit them.
:param timeout: maximum duration to wait to connect to Salt's
IPCMessageServer in seconds. Defaults to 60s
:param kwargs: Any additional keyword arguments passed to this function
will be interpreted as key-value pairs and included in the event data.
This provides a convenient alternative to YAML for simple values.
CLI Example:
.. code-block:: bash
salt-call event.send myco/mytag foo=Foo bar=Bar
salt-call event.send 'myco/mytag' '{foo: Foo, bar: Bar}'
A convenient way to allow Jenkins to execute ``salt-call`` is via sudo. The
following rule in sudoers will allow the ``jenkins`` user to run only the
following command.
``/etc/sudoers`` (allow preserving the environment):
.. code-block:: text
jenkins ALL=(ALL) NOPASSWD:SETENV: /usr/bin/salt-call event.send*
Call Jenkins via sudo (preserve the environment):
.. code-block:: bash
sudo -E salt-call event.send myco/jenkins/build/success with_env='[BUILD_ID, BUILD_URL, GIT_BRANCH, GIT_COMMIT]'
'''
data_dict = {}
if with_env:
if isinstance(with_env, list):
data_dict['environ'] = _dict_subset(with_env, dict(os.environ))
else:
data_dict['environ'] = dict(os.environ)
if with_grains:
if isinstance(with_grains, list):
data_dict['grains'] = _dict_subset(with_grains, __grains__)
else:
data_dict['grains'] = __grains__
if with_pillar:
if isinstance(with_pillar, list):
data_dict['pillar'] = _dict_subset(with_pillar, __pillar__)
else:
data_dict['pillar'] = __pillar__
if with_env_opts:
data_dict['saltenv'] = __opts__.get('saltenv', 'base')
data_dict['pillarenv'] = __opts__.get('pillarenv')
if kwargs:
data_dict.update(kwargs)
# Allow values in the ``data`` arg to override any of the above values.
if isinstance(data, collections.Mapping):
data_dict.update(data)
if __opts__.get('local') or __opts__.get('file_client') == 'local' or __opts__.get('master_type') == 'disable':
return fire(data_dict, tag, timeout=timeout)
else:
return fire_master(data_dict, tag, preload=preload, timeout=timeout) | python | def send(tag,
data=None,
preload=None,
with_env=False,
with_grains=False,
with_pillar=False,
with_env_opts=False,
timeout=60,
**kwargs):
'''
Send an event to the Salt Master
.. versionadded:: 2014.7.0
:param tag: A tag to give the event.
Use slashes to create a namespace for related events. E.g.,
``myco/build/buildserver1/start``, ``myco/build/buildserver1/success``,
``myco/build/buildserver1/failure``.
:param data: A dictionary of data to send in the event.
This is free-form. Send any data points that are needed for whoever is
consuming the event. Arguments on the CLI are interpreted as YAML so
complex data structures are possible.
:param with_env: Include environment variables from the current shell
environment in the event data as ``environ``.. This is a short-hand for
working with systems that seed the environment with relevant data such
as Jenkins.
:type with_env: Specify ``True`` to include all environment variables, or
specify a list of strings of variable names to include.
:param with_grains: Include grains from the current minion in the event
data as ``grains``.
:type with_grains: Specify ``True`` to include all grains, or specify a
list of strings of grain names to include.
:param with_pillar: Include Pillar values from the current minion in the
event data as ``pillar``. Remember Pillar data is often sensitive data
so be careful. This is useful for passing ephemeral Pillar values
through an event. Such as passing the ``pillar={}`` kwarg in
:py:func:`state.sls <salt.modules.state.sls>` from the Master, through
an event on the Minion, then back to the Master.
:type with_pillar: Specify ``True`` to include all Pillar values, or
specify a list of strings of Pillar keys to include. It is a
best-practice to only specify a relevant subset of Pillar data.
:param with_env_opts: Include ``saltenv`` and ``pillarenv`` set on minion
at the moment when event is send into event data.
:type with_env_opts: Specify ``True`` to include ``saltenv`` and
``pillarenv`` values or ``False`` to omit them.
:param timeout: maximum duration to wait to connect to Salt's
IPCMessageServer in seconds. Defaults to 60s
:param kwargs: Any additional keyword arguments passed to this function
will be interpreted as key-value pairs and included in the event data.
This provides a convenient alternative to YAML for simple values.
CLI Example:
.. code-block:: bash
salt-call event.send myco/mytag foo=Foo bar=Bar
salt-call event.send 'myco/mytag' '{foo: Foo, bar: Bar}'
A convenient way to allow Jenkins to execute ``salt-call`` is via sudo. The
following rule in sudoers will allow the ``jenkins`` user to run only the
following command.
``/etc/sudoers`` (allow preserving the environment):
.. code-block:: text
jenkins ALL=(ALL) NOPASSWD:SETENV: /usr/bin/salt-call event.send*
Call Jenkins via sudo (preserve the environment):
.. code-block:: bash
sudo -E salt-call event.send myco/jenkins/build/success with_env='[BUILD_ID, BUILD_URL, GIT_BRANCH, GIT_COMMIT]'
'''
data_dict = {}
if with_env:
if isinstance(with_env, list):
data_dict['environ'] = _dict_subset(with_env, dict(os.environ))
else:
data_dict['environ'] = dict(os.environ)
if with_grains:
if isinstance(with_grains, list):
data_dict['grains'] = _dict_subset(with_grains, __grains__)
else:
data_dict['grains'] = __grains__
if with_pillar:
if isinstance(with_pillar, list):
data_dict['pillar'] = _dict_subset(with_pillar, __pillar__)
else:
data_dict['pillar'] = __pillar__
if with_env_opts:
data_dict['saltenv'] = __opts__.get('saltenv', 'base')
data_dict['pillarenv'] = __opts__.get('pillarenv')
if kwargs:
data_dict.update(kwargs)
# Allow values in the ``data`` arg to override any of the above values.
if isinstance(data, collections.Mapping):
data_dict.update(data)
if __opts__.get('local') or __opts__.get('file_client') == 'local' or __opts__.get('master_type') == 'disable':
return fire(data_dict, tag, timeout=timeout)
else:
return fire_master(data_dict, tag, preload=preload, timeout=timeout) | [
"def",
"send",
"(",
"tag",
",",
"data",
"=",
"None",
",",
"preload",
"=",
"None",
",",
"with_env",
"=",
"False",
",",
"with_grains",
"=",
"False",
",",
"with_pillar",
"=",
"False",
",",
"with_env_opts",
"=",
"False",
",",
"timeout",
"=",
"60",
",",
"... | Send an event to the Salt Master
.. versionadded:: 2014.7.0
:param tag: A tag to give the event.
Use slashes to create a namespace for related events. E.g.,
``myco/build/buildserver1/start``, ``myco/build/buildserver1/success``,
``myco/build/buildserver1/failure``.
:param data: A dictionary of data to send in the event.
This is free-form. Send any data points that are needed for whoever is
consuming the event. Arguments on the CLI are interpreted as YAML so
complex data structures are possible.
:param with_env: Include environment variables from the current shell
environment in the event data as ``environ``.. This is a short-hand for
working with systems that seed the environment with relevant data such
as Jenkins.
:type with_env: Specify ``True`` to include all environment variables, or
specify a list of strings of variable names to include.
:param with_grains: Include grains from the current minion in the event
data as ``grains``.
:type with_grains: Specify ``True`` to include all grains, or specify a
list of strings of grain names to include.
:param with_pillar: Include Pillar values from the current minion in the
event data as ``pillar``. Remember Pillar data is often sensitive data
so be careful. This is useful for passing ephemeral Pillar values
through an event. Such as passing the ``pillar={}`` kwarg in
:py:func:`state.sls <salt.modules.state.sls>` from the Master, through
an event on the Minion, then back to the Master.
:type with_pillar: Specify ``True`` to include all Pillar values, or
specify a list of strings of Pillar keys to include. It is a
best-practice to only specify a relevant subset of Pillar data.
:param with_env_opts: Include ``saltenv`` and ``pillarenv`` set on minion
at the moment when event is send into event data.
:type with_env_opts: Specify ``True`` to include ``saltenv`` and
``pillarenv`` values or ``False`` to omit them.
:param timeout: maximum duration to wait to connect to Salt's
IPCMessageServer in seconds. Defaults to 60s
:param kwargs: Any additional keyword arguments passed to this function
will be interpreted as key-value pairs and included in the event data.
This provides a convenient alternative to YAML for simple values.
CLI Example:
.. code-block:: bash
salt-call event.send myco/mytag foo=Foo bar=Bar
salt-call event.send 'myco/mytag' '{foo: Foo, bar: Bar}'
A convenient way to allow Jenkins to execute ``salt-call`` is via sudo. The
following rule in sudoers will allow the ``jenkins`` user to run only the
following command.
``/etc/sudoers`` (allow preserving the environment):
.. code-block:: text
jenkins ALL=(ALL) NOPASSWD:SETENV: /usr/bin/salt-call event.send*
Call Jenkins via sudo (preserve the environment):
.. code-block:: bash
sudo -E salt-call event.send myco/jenkins/build/success with_env='[BUILD_ID, BUILD_URL, GIT_BRANCH, GIT_COMMIT]' | [
"Send",
"an",
"event",
"to",
"the",
"Salt",
"Master"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/event.py#L131-L247 | train |
saltstack/salt | salt/states/postgres_cluster.py | present | def present(version,
name,
port=None,
encoding=None,
locale=None,
datadir=None,
allow_group_access=None,
data_checksums=None,
wal_segsize=None
):
'''
Ensure that the named cluster is present with the specified properties.
For more information about all of these options see man pg_createcluster(1)
version
Version of the postgresql cluster
name
The name of the cluster
port
Cluster port
encoding
The character encoding scheme to be used in this database
locale
Locale with which to create cluster
datadir
Where the cluster is stored
allow_group_access
Allows users in the same group as the cluster owner to read all cluster files created by initdb
data_checksums
Use checksums on data pages
wal_segsize
Set the WAL segment size, in megabytes
.. versionadded:: 2015.XX
'''
msg = 'Cluster {0}/{1} is already present'.format(version, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': msg}
if __salt__['postgres.cluster_exists'](version, name):
# check cluster config is correct
infos = __salt__['postgres.cluster_list'](verbose=True)
info = infos['{0}/{1}'.format(version, name)]
# TODO: check locale en encoding configs also
if any((port != info['port'] if port else False,
datadir != info['datadir'] if datadir else False,)):
ret['comment'] = 'Cluster {0}/{1} has wrong parameters ' \
'which couldn\'t be changed on fly.' \
.format(version, name)
ret['result'] = False
return ret
# The cluster is not present, add it!
if __opts__.get('test'):
ret['result'] = None
msg = 'Cluster {0}/{1} is set to be created'
ret['comment'] = msg.format(version, name)
return ret
cluster = __salt__['postgres.cluster_create'](
version=version,
name=name,
port=port,
locale=locale,
encoding=encoding,
datadir=datadir,
allow_group_access=allow_group_access,
data_checksums=data_checksums,
wal_segsize=wal_segsize)
if cluster:
msg = 'The cluster {0}/{1} has been created'
ret['comment'] = msg.format(version, name)
ret['changes']['{0}/{1}'.format(version, name)] = 'Present'
else:
msg = 'Failed to create cluster {0}/{1}'
ret['comment'] = msg.format(version, name)
ret['result'] = False
return ret | python | def present(version,
name,
port=None,
encoding=None,
locale=None,
datadir=None,
allow_group_access=None,
data_checksums=None,
wal_segsize=None
):
'''
Ensure that the named cluster is present with the specified properties.
For more information about all of these options see man pg_createcluster(1)
version
Version of the postgresql cluster
name
The name of the cluster
port
Cluster port
encoding
The character encoding scheme to be used in this database
locale
Locale with which to create cluster
datadir
Where the cluster is stored
allow_group_access
Allows users in the same group as the cluster owner to read all cluster files created by initdb
data_checksums
Use checksums on data pages
wal_segsize
Set the WAL segment size, in megabytes
.. versionadded:: 2015.XX
'''
msg = 'Cluster {0}/{1} is already present'.format(version, name)
ret = {'name': name,
'changes': {},
'result': True,
'comment': msg}
if __salt__['postgres.cluster_exists'](version, name):
# check cluster config is correct
infos = __salt__['postgres.cluster_list'](verbose=True)
info = infos['{0}/{1}'.format(version, name)]
# TODO: check locale en encoding configs also
if any((port != info['port'] if port else False,
datadir != info['datadir'] if datadir else False,)):
ret['comment'] = 'Cluster {0}/{1} has wrong parameters ' \
'which couldn\'t be changed on fly.' \
.format(version, name)
ret['result'] = False
return ret
# The cluster is not present, add it!
if __opts__.get('test'):
ret['result'] = None
msg = 'Cluster {0}/{1} is set to be created'
ret['comment'] = msg.format(version, name)
return ret
cluster = __salt__['postgres.cluster_create'](
version=version,
name=name,
port=port,
locale=locale,
encoding=encoding,
datadir=datadir,
allow_group_access=allow_group_access,
data_checksums=data_checksums,
wal_segsize=wal_segsize)
if cluster:
msg = 'The cluster {0}/{1} has been created'
ret['comment'] = msg.format(version, name)
ret['changes']['{0}/{1}'.format(version, name)] = 'Present'
else:
msg = 'Failed to create cluster {0}/{1}'
ret['comment'] = msg.format(version, name)
ret['result'] = False
return ret | [
"def",
"present",
"(",
"version",
",",
"name",
",",
"port",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"locale",
"=",
"None",
",",
"datadir",
"=",
"None",
",",
"allow_group_access",
"=",
"None",
",",
"data_checksums",
"=",
"None",
",",
"wal_segsize"... | Ensure that the named cluster is present with the specified properties.
For more information about all of these options see man pg_createcluster(1)
version
Version of the postgresql cluster
name
The name of the cluster
port
Cluster port
encoding
The character encoding scheme to be used in this database
locale
Locale with which to create cluster
datadir
Where the cluster is stored
allow_group_access
Allows users in the same group as the cluster owner to read all cluster files created by initdb
data_checksums
Use checksums on data pages
wal_segsize
Set the WAL segment size, in megabytes
.. versionadded:: 2015.XX | [
"Ensure",
"that",
"the",
"named",
"cluster",
"is",
"present",
"with",
"the",
"specified",
"properties",
".",
"For",
"more",
"information",
"about",
"all",
"of",
"these",
"options",
"see",
"man",
"pg_createcluster",
"(",
"1",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_cluster.py#L28-L114 | train |
saltstack/salt | salt/states/postgres_cluster.py | absent | def absent(version,
name):
'''
Ensure that the named cluster is absent
version
Version of the postgresql server of the cluster to remove
name
The name of the cluster to remove
.. versionadded:: 2015.XX
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
#check if cluster exists and remove it
if __salt__['postgres.cluster_exists'](version, name):
if __opts__.get('test'):
ret['result'] = None
msg = 'Cluster {0}/{1} is set to be removed'
ret['comment'] = msg.format(version, name)
return ret
if __salt__['postgres.cluster_remove'](version, name, True):
msg = 'Cluster {0}/{1} has been removed'
ret['comment'] = msg.format(version, name)
ret['changes'][name] = 'Absent'
return ret
# fallback
ret['comment'] = 'Cluster {0}/{1} is not present, so it cannot ' \
'be removed'.format(version, name)
return ret | python | def absent(version,
name):
'''
Ensure that the named cluster is absent
version
Version of the postgresql server of the cluster to remove
name
The name of the cluster to remove
.. versionadded:: 2015.XX
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
#check if cluster exists and remove it
if __salt__['postgres.cluster_exists'](version, name):
if __opts__.get('test'):
ret['result'] = None
msg = 'Cluster {0}/{1} is set to be removed'
ret['comment'] = msg.format(version, name)
return ret
if __salt__['postgres.cluster_remove'](version, name, True):
msg = 'Cluster {0}/{1} has been removed'
ret['comment'] = msg.format(version, name)
ret['changes'][name] = 'Absent'
return ret
# fallback
ret['comment'] = 'Cluster {0}/{1} is not present, so it cannot ' \
'be removed'.format(version, name)
return ret | [
"def",
"absent",
"(",
"version",
",",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"#check if cluster exists and remove it",
"if",
"__salt__",
"... | Ensure that the named cluster is absent
version
Version of the postgresql server of the cluster to remove
name
The name of the cluster to remove
.. versionadded:: 2015.XX | [
"Ensure",
"that",
"the",
"named",
"cluster",
"is",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/postgres_cluster.py#L117-L151 | train |
saltstack/salt | salt/returners/splunk.py | _send_splunk | def _send_splunk(event, index_override=None, sourcetype_override=None):
'''
Send the results to Splunk.
Requires the Splunk HTTP Event Collector running on port 8088.
This is available on Splunk Enterprise version 6.3 or higher.
'''
# Get Splunk Options
opts = _get_options()
log.info(str('Options: %s'), # future lint: disable=blacklisted-function
salt.utils.json.dumps(opts))
http_event_collector_key = opts['token']
http_event_collector_host = opts['indexer']
# Set up the collector
splunk_event = http_event_collector(http_event_collector_key, http_event_collector_host)
# init the payload
payload = {}
# Set up the event metadata
if index_override is None:
payload.update({"index": opts['index']})
else:
payload.update({"index": index_override})
if sourcetype_override is None:
payload.update({"sourcetype": opts['sourcetype']})
else:
payload.update({"index": sourcetype_override})
# Add the event
payload.update({"event": event})
log.info(str('Payload: %s'), # future lint: disable=blacklisted-function
salt.utils.json.dumps(payload))
# Fire it off
splunk_event.sendEvent(payload)
return True | python | def _send_splunk(event, index_override=None, sourcetype_override=None):
'''
Send the results to Splunk.
Requires the Splunk HTTP Event Collector running on port 8088.
This is available on Splunk Enterprise version 6.3 or higher.
'''
# Get Splunk Options
opts = _get_options()
log.info(str('Options: %s'), # future lint: disable=blacklisted-function
salt.utils.json.dumps(opts))
http_event_collector_key = opts['token']
http_event_collector_host = opts['indexer']
# Set up the collector
splunk_event = http_event_collector(http_event_collector_key, http_event_collector_host)
# init the payload
payload = {}
# Set up the event metadata
if index_override is None:
payload.update({"index": opts['index']})
else:
payload.update({"index": index_override})
if sourcetype_override is None:
payload.update({"sourcetype": opts['sourcetype']})
else:
payload.update({"index": sourcetype_override})
# Add the event
payload.update({"event": event})
log.info(str('Payload: %s'), # future lint: disable=blacklisted-function
salt.utils.json.dumps(payload))
# Fire it off
splunk_event.sendEvent(payload)
return True | [
"def",
"_send_splunk",
"(",
"event",
",",
"index_override",
"=",
"None",
",",
"sourcetype_override",
"=",
"None",
")",
":",
"# Get Splunk Options",
"opts",
"=",
"_get_options",
"(",
")",
"log",
".",
"info",
"(",
"str",
"(",
"'Options: %s'",
")",
",",
"# futu... | Send the results to Splunk.
Requires the Splunk HTTP Event Collector running on port 8088.
This is available on Splunk Enterprise version 6.3 or higher. | [
"Send",
"the",
"results",
"to",
"Splunk",
".",
"Requires",
"the",
"Splunk",
"HTTP",
"Event",
"Collector",
"running",
"on",
"port",
"8088",
".",
"This",
"is",
"available",
"on",
"Splunk",
"Enterprise",
"version",
"6",
".",
"3",
"or",
"higher",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/splunk.py#L70-L104 | train |
saltstack/salt | salt/output/dson.py | output | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print the output data in JSON
'''
try:
dump_opts = {'indent': 4, 'default': repr}
if 'output_indent' in __opts__:
indent = __opts__.get('output_indent')
sort_keys = False
if indent == 'pretty':
indent = 4
sort_keys = True
elif isinstance(indent, six.integer_types):
if indent >= 0:
indent = indent
else:
indent = None
dump_opts['indent'] = indent
dump_opts['sort_keys'] = sort_keys
return dson.dumps(data, **dump_opts)
except UnicodeDecodeError as exc:
log.error('Unable to serialize output to dson')
return dson.dumps(
{'error': 'Unable to serialize output to DSON',
'message': six.text_type(exc)}
)
except TypeError:
log.debug('An error occurred while outputting DSON', exc_info=True)
# Return valid JSON for unserializable objects
return dson.dumps({}) | python | def output(data, **kwargs): # pylint: disable=unused-argument
'''
Print the output data in JSON
'''
try:
dump_opts = {'indent': 4, 'default': repr}
if 'output_indent' in __opts__:
indent = __opts__.get('output_indent')
sort_keys = False
if indent == 'pretty':
indent = 4
sort_keys = True
elif isinstance(indent, six.integer_types):
if indent >= 0:
indent = indent
else:
indent = None
dump_opts['indent'] = indent
dump_opts['sort_keys'] = sort_keys
return dson.dumps(data, **dump_opts)
except UnicodeDecodeError as exc:
log.error('Unable to serialize output to dson')
return dson.dumps(
{'error': 'Unable to serialize output to DSON',
'message': six.text_type(exc)}
)
except TypeError:
log.debug('An error occurred while outputting DSON', exc_info=True)
# Return valid JSON for unserializable objects
return dson.dumps({}) | [
"def",
"output",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"try",
":",
"dump_opts",
"=",
"{",
"'indent'",
":",
"4",
",",
"'default'",
":",
"repr",
"}",
"if",
"'output_indent'",
"in",
"__opts__",
":",
"indent",
"="... | Print the output data in JSON | [
"Print",
"the",
"output",
"data",
"in",
"JSON"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/output/dson.py#L37-L74 | train |
saltstack/salt | salt/states/serverdensity_device.py | _get_salt_params | def _get_salt_params():
'''
Try to get all sort of parameters for Server Density server info.
NOTE: Missing publicDNS and publicIPs parameters. There might be way of
getting them with salt-cloud.
'''
all_stats = __salt__['status.all_status']()
all_grains = __salt__['grains.items']()
params = {}
try:
params['name'] = all_grains['id']
params['hostname'] = all_grains['host']
if all_grains['kernel'] == 'Darwin':
sd_os = {'code': 'mac', 'name': 'Mac'}
else:
sd_os = {'code': all_grains['kernel'].lower(), 'name': all_grains['kernel']}
params['os'] = salt.utils.json.dumps(sd_os)
params['cpuCores'] = all_stats['cpuinfo']['cpu cores']
params['installedRAM'] = six.text_type(int(all_stats['meminfo']['MemTotal']['value']) / 1024)
params['swapSpace'] = six.text_type(int(all_stats['meminfo']['SwapTotal']['value']) / 1024)
params['privateIPs'] = salt.utils.json.dumps(all_grains['fqdn_ip4'])
params['privateDNS'] = salt.utils.json.dumps(all_grains['fqdn'])
except KeyError:
pass
return params | python | def _get_salt_params():
'''
Try to get all sort of parameters for Server Density server info.
NOTE: Missing publicDNS and publicIPs parameters. There might be way of
getting them with salt-cloud.
'''
all_stats = __salt__['status.all_status']()
all_grains = __salt__['grains.items']()
params = {}
try:
params['name'] = all_grains['id']
params['hostname'] = all_grains['host']
if all_grains['kernel'] == 'Darwin':
sd_os = {'code': 'mac', 'name': 'Mac'}
else:
sd_os = {'code': all_grains['kernel'].lower(), 'name': all_grains['kernel']}
params['os'] = salt.utils.json.dumps(sd_os)
params['cpuCores'] = all_stats['cpuinfo']['cpu cores']
params['installedRAM'] = six.text_type(int(all_stats['meminfo']['MemTotal']['value']) / 1024)
params['swapSpace'] = six.text_type(int(all_stats['meminfo']['SwapTotal']['value']) / 1024)
params['privateIPs'] = salt.utils.json.dumps(all_grains['fqdn_ip4'])
params['privateDNS'] = salt.utils.json.dumps(all_grains['fqdn'])
except KeyError:
pass
return params | [
"def",
"_get_salt_params",
"(",
")",
":",
"all_stats",
"=",
"__salt__",
"[",
"'status.all_status'",
"]",
"(",
")",
"all_grains",
"=",
"__salt__",
"[",
"'grains.items'",
"]",
"(",
")",
"params",
"=",
"{",
"}",
"try",
":",
"params",
"[",
"'name'",
"]",
"="... | Try to get all sort of parameters for Server Density server info.
NOTE: Missing publicDNS and publicIPs parameters. There might be way of
getting them with salt-cloud. | [
"Try",
"to",
"get",
"all",
"sort",
"of",
"parameters",
"for",
"Server",
"Density",
"server",
"info",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/serverdensity_device.py#L69-L95 | train |
saltstack/salt | salt/states/serverdensity_device.py | monitored | def monitored(name, group=None, salt_name=True, salt_params=True, agent_version=1, **params):
'''
Device is monitored with Server Density.
name
Device name in Server Density.
salt_name
If ``True`` (default), takes the name from the ``id`` grain. If
``False``, the provided name is used.
group
Group name under with device will appear in Server Density dashboard.
Default - `None`.
agent_version
The agent version you want to use. Valid values are 1 or 2.
Default - 1.
salt_params
If ``True`` (default), needed config parameters will be sourced from
grains and from :mod:`status.all_status
<salt.modules.status.all_status>`.
params
Add parameters that you want to appear in the Server Density dashboard.
Will overwrite the `salt_params` parameters. For more info, see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
Usage example:
.. code-block:: yaml
'server_name':
serverdensity_device.monitored
.. code-block:: yaml
'server_name':
serverdensity_device.monitored:
- group: web-servers
.. code-block:: yaml
'my_special_server':
serverdensity_device.monitored:
- salt_name: False
- group: web-servers
- cpuCores: 2
- os: '{"code": "linux", "name": "Linux"}'
'''
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
params_from_salt = _get_salt_params()
if salt_name:
name = params_from_salt.pop('name')
ret['name'] = name
else:
params_from_salt.pop('name')
if group:
params['group'] = group
if agent_version != 2:
# Anything different from 2 will fallback into the v1.
agent_version = 1
# override salt_params with given params
if salt_params:
for key, value in six.iteritems(params):
params_from_salt[key] = value
params_to_use = params_from_salt
else:
params_to_use = params
device_in_sd = True if __salt__['serverdensity_device.ls'](name=name) else False
sd_agent_installed = True if 'sd-agent' in __salt__['pkg.list_pkgs']() else False
if device_in_sd and sd_agent_installed:
ret['result'] = True
ret['comment'] = 'Such server name already exists in this Server Density account. And sd-agent is installed'
ret['changes'] = {}
return ret
if __opts__['test']:
if not device_in_sd or not sd_agent_installed:
ret['result'] = None
ret['comment'] = 'Server Density agent is set to be installed and/or device created in the Server Density DB'
return ret
else:
ret['result'] = None
ret['comment'] = 'Server Density agent is already installed, or device already exists'
return ret
elif device_in_sd:
device = __salt__['serverdensity_device.ls'](name=name)[0]
agent_key = device['agentKey']
ret['comment'] = 'Device was already in Server Density db.'
if not device_in_sd:
device = __salt__['serverdensity_device.create'](name, **params_from_salt)
agent_key = device['agentKey']
ret['comment'] = 'Device created in Server Density db.'
ret['changes'] = {'device_created': device}
else:
ret['result'] = False
ret['comment'] = 'Failed to create device in Server Density DB and this device does not exist in db either.'
ret['changes'] = {}
installed_agent = __salt__['serverdensity_device.install_agent'](agent_key, agent_version)
ret['result'] = True
ret['comment'] = 'Successfully installed agent and created device in Server Density db.'
ret['changes'] = {'created_device': device, 'installed_agent': installed_agent}
return ret | python | def monitored(name, group=None, salt_name=True, salt_params=True, agent_version=1, **params):
'''
Device is monitored with Server Density.
name
Device name in Server Density.
salt_name
If ``True`` (default), takes the name from the ``id`` grain. If
``False``, the provided name is used.
group
Group name under with device will appear in Server Density dashboard.
Default - `None`.
agent_version
The agent version you want to use. Valid values are 1 or 2.
Default - 1.
salt_params
If ``True`` (default), needed config parameters will be sourced from
grains and from :mod:`status.all_status
<salt.modules.status.all_status>`.
params
Add parameters that you want to appear in the Server Density dashboard.
Will overwrite the `salt_params` parameters. For more info, see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
Usage example:
.. code-block:: yaml
'server_name':
serverdensity_device.monitored
.. code-block:: yaml
'server_name':
serverdensity_device.monitored:
- group: web-servers
.. code-block:: yaml
'my_special_server':
serverdensity_device.monitored:
- salt_name: False
- group: web-servers
- cpuCores: 2
- os: '{"code": "linux", "name": "Linux"}'
'''
ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}
params_from_salt = _get_salt_params()
if salt_name:
name = params_from_salt.pop('name')
ret['name'] = name
else:
params_from_salt.pop('name')
if group:
params['group'] = group
if agent_version != 2:
# Anything different from 2 will fallback into the v1.
agent_version = 1
# override salt_params with given params
if salt_params:
for key, value in six.iteritems(params):
params_from_salt[key] = value
params_to_use = params_from_salt
else:
params_to_use = params
device_in_sd = True if __salt__['serverdensity_device.ls'](name=name) else False
sd_agent_installed = True if 'sd-agent' in __salt__['pkg.list_pkgs']() else False
if device_in_sd and sd_agent_installed:
ret['result'] = True
ret['comment'] = 'Such server name already exists in this Server Density account. And sd-agent is installed'
ret['changes'] = {}
return ret
if __opts__['test']:
if not device_in_sd or not sd_agent_installed:
ret['result'] = None
ret['comment'] = 'Server Density agent is set to be installed and/or device created in the Server Density DB'
return ret
else:
ret['result'] = None
ret['comment'] = 'Server Density agent is already installed, or device already exists'
return ret
elif device_in_sd:
device = __salt__['serverdensity_device.ls'](name=name)[0]
agent_key = device['agentKey']
ret['comment'] = 'Device was already in Server Density db.'
if not device_in_sd:
device = __salt__['serverdensity_device.create'](name, **params_from_salt)
agent_key = device['agentKey']
ret['comment'] = 'Device created in Server Density db.'
ret['changes'] = {'device_created': device}
else:
ret['result'] = False
ret['comment'] = 'Failed to create device in Server Density DB and this device does not exist in db either.'
ret['changes'] = {}
installed_agent = __salt__['serverdensity_device.install_agent'](agent_key, agent_version)
ret['result'] = True
ret['comment'] = 'Successfully installed agent and created device in Server Density db.'
ret['changes'] = {'created_device': device, 'installed_agent': installed_agent}
return ret | [
"def",
"monitored",
"(",
"name",
",",
"group",
"=",
"None",
",",
"salt_name",
"=",
"True",
",",
"salt_params",
"=",
"True",
",",
"agent_version",
"=",
"1",
",",
"*",
"*",
"params",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
... | Device is monitored with Server Density.
name
Device name in Server Density.
salt_name
If ``True`` (default), takes the name from the ``id`` grain. If
``False``, the provided name is used.
group
Group name under with device will appear in Server Density dashboard.
Default - `None`.
agent_version
The agent version you want to use. Valid values are 1 or 2.
Default - 1.
salt_params
If ``True`` (default), needed config parameters will be sourced from
grains and from :mod:`status.all_status
<salt.modules.status.all_status>`.
params
Add parameters that you want to appear in the Server Density dashboard.
Will overwrite the `salt_params` parameters. For more info, see the
`API docs`__.
.. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating
Usage example:
.. code-block:: yaml
'server_name':
serverdensity_device.monitored
.. code-block:: yaml
'server_name':
serverdensity_device.monitored:
- group: web-servers
.. code-block:: yaml
'my_special_server':
serverdensity_device.monitored:
- salt_name: False
- group: web-servers
- cpuCores: 2
- os: '{"code": "linux", "name": "Linux"}' | [
"Device",
"is",
"monitored",
"with",
"Server",
"Density",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/serverdensity_device.py#L98-L215 | train |
saltstack/salt | salt/queues/sqlite_queue.py | _conn | def _conn(queue):
'''
Return an sqlite connection
'''
queue_dir = __opts__['sqlite_queue_dir']
db = os.path.join(queue_dir, '{0}.db'.format(queue))
log.debug('Connecting to: %s', db)
con = sqlite3.connect(db)
tables = _list_tables(con)
if queue not in tables:
_create_table(con, queue)
return con | python | def _conn(queue):
'''
Return an sqlite connection
'''
queue_dir = __opts__['sqlite_queue_dir']
db = os.path.join(queue_dir, '{0}.db'.format(queue))
log.debug('Connecting to: %s', db)
con = sqlite3.connect(db)
tables = _list_tables(con)
if queue not in tables:
_create_table(con, queue)
return con | [
"def",
"_conn",
"(",
"queue",
")",
":",
"queue_dir",
"=",
"__opts__",
"[",
"'sqlite_queue_dir'",
"]",
"db",
"=",
"os",
".",
"path",
".",
"join",
"(",
"queue_dir",
",",
"'{0}.db'",
".",
"format",
"(",
"queue",
")",
")",
"log",
".",
"debug",
"(",
"'Con... | Return an sqlite connection | [
"Return",
"an",
"sqlite",
"connection"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L40-L52 | train |
saltstack/salt | salt/queues/sqlite_queue.py | _list_items | def _list_items(queue):
'''
Private function to list contents of a queue
'''
con = _conn(queue)
with con:
cur = con.cursor()
cmd = 'SELECT name FROM {0}'.format(queue)
log.debug('SQL Query: %s', cmd)
cur.execute(cmd)
contents = cur.fetchall()
return contents | python | def _list_items(queue):
'''
Private function to list contents of a queue
'''
con = _conn(queue)
with con:
cur = con.cursor()
cmd = 'SELECT name FROM {0}'.format(queue)
log.debug('SQL Query: %s', cmd)
cur.execute(cmd)
contents = cur.fetchall()
return contents | [
"def",
"_list_items",
"(",
"queue",
")",
":",
"con",
"=",
"_conn",
"(",
"queue",
")",
"with",
"con",
":",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"cmd",
"=",
"'SELECT name FROM {0}'",
".",
"format",
"(",
"queue",
")",
"log",
".",
"debug",
"(",
... | Private function to list contents of a queue | [
"Private",
"function",
"to",
"list",
"contents",
"of",
"a",
"queue"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L75-L86 | train |
saltstack/salt | salt/queues/sqlite_queue.py | _list_queues | def _list_queues():
'''
Return a list of sqlite databases in the queue_dir
'''
queue_dir = __opts__['sqlite_queue_dir']
files = os.path.join(queue_dir, '*.db')
paths = glob.glob(files)
queues = [os.path.splitext(os.path.basename(item))[0] for item in paths]
return queues | python | def _list_queues():
'''
Return a list of sqlite databases in the queue_dir
'''
queue_dir = __opts__['sqlite_queue_dir']
files = os.path.join(queue_dir, '*.db')
paths = glob.glob(files)
queues = [os.path.splitext(os.path.basename(item))[0] for item in paths]
return queues | [
"def",
"_list_queues",
"(",
")",
":",
"queue_dir",
"=",
"__opts__",
"[",
"'sqlite_queue_dir'",
"]",
"files",
"=",
"os",
".",
"path",
".",
"join",
"(",
"queue_dir",
",",
"'*.db'",
")",
"paths",
"=",
"glob",
".",
"glob",
"(",
"files",
")",
"queues",
"=",... | Return a list of sqlite databases in the queue_dir | [
"Return",
"a",
"list",
"of",
"sqlite",
"databases",
"in",
"the",
"queue_dir"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L89-L98 | train |
saltstack/salt | salt/queues/sqlite_queue.py | list_items | def list_items(queue):
'''
List contents of a queue
'''
itemstuple = _list_items(queue)
items = [item[0] for item in itemstuple]
return items | python | def list_items(queue):
'''
List contents of a queue
'''
itemstuple = _list_items(queue)
items = [item[0] for item in itemstuple]
return items | [
"def",
"list_items",
"(",
"queue",
")",
":",
"itemstuple",
"=",
"_list_items",
"(",
"queue",
")",
"items",
"=",
"[",
"item",
"[",
"0",
"]",
"for",
"item",
"in",
"itemstuple",
"]",
"return",
"items"
] | List contents of a queue | [
"List",
"contents",
"of",
"a",
"queue"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L109-L115 | train |
saltstack/salt | salt/queues/sqlite_queue.py | _quote_escape | def _quote_escape(item):
'''
Make sure single quotes are escaped properly in sqlite3 fashion.
e.g.: ' becomes ''
'''
rex_sqlquote = re.compile("'", re.M)
return rex_sqlquote.sub("''", item) | python | def _quote_escape(item):
'''
Make sure single quotes are escaped properly in sqlite3 fashion.
e.g.: ' becomes ''
'''
rex_sqlquote = re.compile("'", re.M)
return rex_sqlquote.sub("''", item) | [
"def",
"_quote_escape",
"(",
"item",
")",
":",
"rex_sqlquote",
"=",
"re",
".",
"compile",
"(",
"\"'\"",
",",
"re",
".",
"M",
")",
"return",
"rex_sqlquote",
".",
"sub",
"(",
"\"''\"",
",",
"item",
")"
] | Make sure single quotes are escaped properly in sqlite3 fashion.
e.g.: ' becomes '' | [
"Make",
"sure",
"single",
"quotes",
"are",
"escaped",
"properly",
"in",
"sqlite3",
"fashion",
".",
"e",
".",
"g",
".",
":",
"becomes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L126-L134 | train |
saltstack/salt | salt/queues/sqlite_queue.py | delete | def delete(queue, items):
'''
Delete an item or items from a queue
'''
con = _conn(queue)
with con:
cur = con.cursor()
if isinstance(items, six.string_types):
items = _quote_escape(items)
cmd = """DELETE FROM {0} WHERE name = '{1}'""".format(queue, items)
log.debug('SQL Query: %s', cmd)
cur.execute(cmd)
return True
if isinstance(items, list):
items = [_quote_escape(el) for el in items]
cmd = 'DELETE FROM {0} WHERE name = ?'.format(queue)
log.debug('SQL Query: %s', cmd)
newitems = []
for item in items:
newitems.append((item,))
# we need a list of one item tuples here
cur.executemany(cmd, newitems)
if isinstance(items, dict):
items = salt.utils.json.dumps(items).replace('"', "'")
items = _quote_escape(items)
cmd = ("""DELETE FROM {0} WHERE name = '{1}'""").format(queue, items) # future lint: disable=blacklisted-function
log.debug('SQL Query: %s', cmd)
cur.execute(cmd)
return True
return True | python | def delete(queue, items):
'''
Delete an item or items from a queue
'''
con = _conn(queue)
with con:
cur = con.cursor()
if isinstance(items, six.string_types):
items = _quote_escape(items)
cmd = """DELETE FROM {0} WHERE name = '{1}'""".format(queue, items)
log.debug('SQL Query: %s', cmd)
cur.execute(cmd)
return True
if isinstance(items, list):
items = [_quote_escape(el) for el in items]
cmd = 'DELETE FROM {0} WHERE name = ?'.format(queue)
log.debug('SQL Query: %s', cmd)
newitems = []
for item in items:
newitems.append((item,))
# we need a list of one item tuples here
cur.executemany(cmd, newitems)
if isinstance(items, dict):
items = salt.utils.json.dumps(items).replace('"', "'")
items = _quote_escape(items)
cmd = ("""DELETE FROM {0} WHERE name = '{1}'""").format(queue, items) # future lint: disable=blacklisted-function
log.debug('SQL Query: %s', cmd)
cur.execute(cmd)
return True
return True | [
"def",
"delete",
"(",
"queue",
",",
"items",
")",
":",
"con",
"=",
"_conn",
"(",
"queue",
")",
"with",
"con",
":",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"if",
"isinstance",
"(",
"items",
",",
"six",
".",
"string_types",
")",
":",
"items",
"... | Delete an item or items from a queue | [
"Delete",
"an",
"item",
"or",
"items",
"from",
"a",
"queue"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L179-L208 | train |
saltstack/salt | salt/queues/sqlite_queue.py | pop | def pop(queue, quantity=1, is_runner=False):
'''
Pop one or more or all items from the queue return them.
'''
cmd = 'SELECT name FROM {0}'.format(queue)
if quantity != 'all':
try:
quantity = int(quantity)
except ValueError as exc:
error_txt = ('Quantity must be an integer or "all".\n'
'Error: "{0}".'.format(exc))
raise SaltInvocationError(error_txt)
cmd = ''.join([cmd, ' LIMIT {0}'.format(quantity)])
log.debug('SQL Query: %s', cmd)
con = _conn(queue)
items = []
with con:
cur = con.cursor()
result = cur.execute(cmd).fetchall()
if result:
items = [item[0] for item in result]
itemlist = '","'.join(items)
_quote_escape(itemlist)
del_cmd = '''DELETE FROM {0} WHERE name IN ("{1}")'''.format(
queue, itemlist)
log.debug('SQL Query: %s', del_cmd)
cur.execute(del_cmd)
con.commit()
if is_runner:
items = [salt.utils.json.loads(item[0].replace("'", '"')) for item in result]
log.info(items)
return items | python | def pop(queue, quantity=1, is_runner=False):
'''
Pop one or more or all items from the queue return them.
'''
cmd = 'SELECT name FROM {0}'.format(queue)
if quantity != 'all':
try:
quantity = int(quantity)
except ValueError as exc:
error_txt = ('Quantity must be an integer or "all".\n'
'Error: "{0}".'.format(exc))
raise SaltInvocationError(error_txt)
cmd = ''.join([cmd, ' LIMIT {0}'.format(quantity)])
log.debug('SQL Query: %s', cmd)
con = _conn(queue)
items = []
with con:
cur = con.cursor()
result = cur.execute(cmd).fetchall()
if result:
items = [item[0] for item in result]
itemlist = '","'.join(items)
_quote_escape(itemlist)
del_cmd = '''DELETE FROM {0} WHERE name IN ("{1}")'''.format(
queue, itemlist)
log.debug('SQL Query: %s', del_cmd)
cur.execute(del_cmd)
con.commit()
if is_runner:
items = [salt.utils.json.loads(item[0].replace("'", '"')) for item in result]
log.info(items)
return items | [
"def",
"pop",
"(",
"queue",
",",
"quantity",
"=",
"1",
",",
"is_runner",
"=",
"False",
")",
":",
"cmd",
"=",
"'SELECT name FROM {0}'",
".",
"format",
"(",
"queue",
")",
"if",
"quantity",
"!=",
"'all'",
":",
"try",
":",
"quantity",
"=",
"int",
"(",
"q... | Pop one or more or all items from the queue return them. | [
"Pop",
"one",
"or",
"more",
"or",
"all",
"items",
"from",
"the",
"queue",
"return",
"them",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/queues/sqlite_queue.py#L211-L244 | train |
saltstack/salt | salt/modules/boto_sns.py | get_all_topics | def get_all_topics(region=None, key=None, keyid=None, profile=None):
'''
Returns a list of the all topics..
CLI example::
salt myminion boto_sns.get_all_topics
'''
cache_key = _cache_get_key()
try:
return __context__[cache_key]
except KeyError:
pass
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
__context__[cache_key] = {}
# TODO: support >100 SNS topics (via NextToken)
topics = conn.get_all_topics()
for t in topics['ListTopicsResponse']['ListTopicsResult']['Topics']:
short_name = t['TopicArn'].split(':')[-1]
__context__[cache_key][short_name] = t['TopicArn']
return __context__[cache_key] | python | def get_all_topics(region=None, key=None, keyid=None, profile=None):
'''
Returns a list of the all topics..
CLI example::
salt myminion boto_sns.get_all_topics
'''
cache_key = _cache_get_key()
try:
return __context__[cache_key]
except KeyError:
pass
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
__context__[cache_key] = {}
# TODO: support >100 SNS topics (via NextToken)
topics = conn.get_all_topics()
for t in topics['ListTopicsResponse']['ListTopicsResult']['Topics']:
short_name = t['TopicArn'].split(':')[-1]
__context__[cache_key][short_name] = t['TopicArn']
return __context__[cache_key] | [
"def",
"get_all_topics",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"cache_key",
"=",
"_cache_get_key",
"(",
")",
"try",
":",
"return",
"__context__",
"[",
"cache_key",
"]",
"e... | Returns a list of the all topics..
CLI example::
salt myminion boto_sns.get_all_topics | [
"Returns",
"a",
"list",
"of",
"the",
"all",
"topics",
".."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L78-L99 | train |
saltstack/salt | salt/modules/boto_sns.py | exists | def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an SNS topic exists.
CLI example::
salt myminion boto_sns.exists mytopic region=us-east-1
'''
topics = get_all_topics(region=region, key=key, keyid=keyid,
profile=profile)
if name.startswith('arn:aws:sns:'):
return name in list(topics.values())
else:
return name in list(topics.keys()) | python | def exists(name, region=None, key=None, keyid=None, profile=None):
'''
Check to see if an SNS topic exists.
CLI example::
salt myminion boto_sns.exists mytopic region=us-east-1
'''
topics = get_all_topics(region=region, key=key, keyid=keyid,
profile=profile)
if name.startswith('arn:aws:sns:'):
return name in list(topics.values())
else:
return name in list(topics.keys()) | [
"def",
"exists",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"topics",
"=",
"get_all_topics",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid"... | Check to see if an SNS topic exists.
CLI example::
salt myminion boto_sns.exists mytopic region=us-east-1 | [
"Check",
"to",
"see",
"if",
"an",
"SNS",
"topic",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L102-L115 | train |
saltstack/salt | salt/modules/boto_sns.py | create | def create(name, region=None, key=None, keyid=None, profile=None):
'''
Create an SNS topic.
CLI example to create a topic::
salt myminion boto_sns.create mytopic region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.create_topic(name)
log.info('Created SNS topic %s', name)
_invalidate_cache()
return True | python | def create(name, region=None, key=None, keyid=None, profile=None):
'''
Create an SNS topic.
CLI example to create a topic::
salt myminion boto_sns.create mytopic region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.create_topic(name)
log.info('Created SNS topic %s', name)
_invalidate_cache()
return True | [
"def",
"create",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"="... | Create an SNS topic.
CLI example to create a topic::
salt myminion boto_sns.create mytopic region=us-east-1 | [
"Create",
"an",
"SNS",
"topic",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L118-L130 | train |
saltstack/salt | salt/modules/boto_sns.py | delete | def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete an SNS topic.
CLI example to delete a topic::
salt myminion boto_sns.delete mytopic region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_topic(get_arn(name, region, key, keyid, profile))
log.info('Deleted SNS topic %s', name)
_invalidate_cache()
return True | python | def delete(name, region=None, key=None, keyid=None, profile=None):
'''
Delete an SNS topic.
CLI example to delete a topic::
salt myminion boto_sns.delete mytopic region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_topic(get_arn(name, region, key, keyid, profile))
log.info('Deleted SNS topic %s', name)
_invalidate_cache()
return True | [
"def",
"delete",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"="... | Delete an SNS topic.
CLI example to delete a topic::
salt myminion boto_sns.delete mytopic region=us-east-1 | [
"Delete",
"an",
"SNS",
"topic",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L133-L145 | train |
saltstack/salt | salt/modules/boto_sns.py | get_all_subscriptions_by_topic | def get_all_subscriptions_by_topic(name, region=None, key=None, keyid=None, profile=None):
'''
Get list of all subscriptions to a specific topic.
CLI example to delete a topic::
salt myminion boto_sns.get_all_subscriptions_by_topic mytopic region=us-east-1
'''
cache_key = _subscriptions_cache_key(name)
try:
return __context__[cache_key]
except KeyError:
pass
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.get_all_subscriptions_by_topic(get_arn(name, region, key, keyid, profile))
__context__[cache_key] = ret['ListSubscriptionsByTopicResponse']['ListSubscriptionsByTopicResult']['Subscriptions']
return __context__[cache_key] | python | def get_all_subscriptions_by_topic(name, region=None, key=None, keyid=None, profile=None):
'''
Get list of all subscriptions to a specific topic.
CLI example to delete a topic::
salt myminion boto_sns.get_all_subscriptions_by_topic mytopic region=us-east-1
'''
cache_key = _subscriptions_cache_key(name)
try:
return __context__[cache_key]
except KeyError:
pass
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
ret = conn.get_all_subscriptions_by_topic(get_arn(name, region, key, keyid, profile))
__context__[cache_key] = ret['ListSubscriptionsByTopicResponse']['ListSubscriptionsByTopicResult']['Subscriptions']
return __context__[cache_key] | [
"def",
"get_all_subscriptions_by_topic",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"cache_key",
"=",
"_subscriptions_cache_key",
"(",
"name",
")",
"try",
":",
"return... | Get list of all subscriptions to a specific topic.
CLI example to delete a topic::
salt myminion boto_sns.get_all_subscriptions_by_topic mytopic region=us-east-1 | [
"Get",
"list",
"of",
"all",
"subscriptions",
"to",
"a",
"specific",
"topic",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L148-L165 | train |
saltstack/salt | salt/modules/boto_sns.py | subscribe | def subscribe(topic, protocol, endpoint, region=None, key=None, keyid=None, profile=None):
'''
Subscribe to a Topic.
CLI example to delete a topic::
salt myminion boto_sns.subscribe mytopic https https://www.example.com/sns-endpoint region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.subscribe(get_arn(topic, region, key, keyid, profile), protocol, endpoint)
log.info('Subscribe %s %s to %s topic', protocol, endpoint, topic)
try:
del __context__[_subscriptions_cache_key(topic)]
except KeyError:
pass
return True | python | def subscribe(topic, protocol, endpoint, region=None, key=None, keyid=None, profile=None):
'''
Subscribe to a Topic.
CLI example to delete a topic::
salt myminion boto_sns.subscribe mytopic https https://www.example.com/sns-endpoint region=us-east-1
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.subscribe(get_arn(topic, region, key, keyid, profile), protocol, endpoint)
log.info('Subscribe %s %s to %s topic', protocol, endpoint, topic)
try:
del __context__[_subscriptions_cache_key(topic)]
except KeyError:
pass
return True | [
"def",
"subscribe",
"(",
"topic",
",",
"protocol",
",",
"endpoint",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... | Subscribe to a Topic.
CLI example to delete a topic::
salt myminion boto_sns.subscribe mytopic https https://www.example.com/sns-endpoint region=us-east-1 | [
"Subscribe",
"to",
"a",
"Topic",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L168-L183 | train |
saltstack/salt | salt/modules/boto_sns.py | unsubscribe | def unsubscribe(topic, subscription_arn, region=None, key=None, keyid=None, profile=None):
'''
Unsubscribe a specific SubscriptionArn of a topic.
CLI Example:
.. code-block:: bash
salt myminion boto_sns.unsubscribe my_topic my_subscription_arn region=us-east-1
.. versionadded:: 2016.11.0
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if subscription_arn.startswith('arn:aws:sns:') is False:
return False
try:
conn.unsubscribe(subscription_arn)
log.info('Unsubscribe %s to %s topic', subscription_arn, topic)
except Exception as e:
log.error('Unsubscribe Error', exc_info=True)
return False
else:
__context__.pop(_subscriptions_cache_key(topic), None)
return True | python | def unsubscribe(topic, subscription_arn, region=None, key=None, keyid=None, profile=None):
'''
Unsubscribe a specific SubscriptionArn of a topic.
CLI Example:
.. code-block:: bash
salt myminion boto_sns.unsubscribe my_topic my_subscription_arn region=us-east-1
.. versionadded:: 2016.11.0
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if subscription_arn.startswith('arn:aws:sns:') is False:
return False
try:
conn.unsubscribe(subscription_arn)
log.info('Unsubscribe %s to %s topic', subscription_arn, topic)
except Exception as e:
log.error('Unsubscribe Error', exc_info=True)
return False
else:
__context__.pop(_subscriptions_cache_key(topic), None)
return True | [
"def",
"unsubscribe",
"(",
"topic",
",",
"subscription_arn",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=... | Unsubscribe a specific SubscriptionArn of a topic.
CLI Example:
.. code-block:: bash
salt myminion boto_sns.unsubscribe my_topic my_subscription_arn region=us-east-1
.. versionadded:: 2016.11.0 | [
"Unsubscribe",
"a",
"specific",
"SubscriptionArn",
"of",
"a",
"topic",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L186-L211 | train |
saltstack/salt | salt/modules/boto_sns.py | get_arn | def get_arn(name, region=None, key=None, keyid=None, profile=None):
'''
Returns the full ARN for a given topic name.
CLI example::
salt myminion boto_sns.get_arn mytopic
'''
if name.startswith('arn:aws:sns:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
return 'arn:aws:sns:{0}:{1}:{2}'.format(_get_region(region, profile),
account_id, name) | python | def get_arn(name, region=None, key=None, keyid=None, profile=None):
'''
Returns the full ARN for a given topic name.
CLI example::
salt myminion boto_sns.get_arn mytopic
'''
if name.startswith('arn:aws:sns:'):
return name
account_id = __salt__['boto_iam.get_account_id'](
region=region, key=key, keyid=keyid, profile=profile
)
return 'arn:aws:sns:{0}:{1}:{2}'.format(_get_region(region, profile),
account_id, name) | [
"def",
"get_arn",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"if",
"name",
".",
"startswith",
"(",
"'arn:aws:sns:'",
")",
":",
"return",
"name",
"account_id",
"=... | Returns the full ARN for a given topic name.
CLI example::
salt myminion boto_sns.get_arn mytopic | [
"Returns",
"the",
"full",
"ARN",
"for",
"a",
"given",
"topic",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_sns.py#L214-L229 | train |
saltstack/salt | salt/utils/asynchronous.py | current_ioloop | def current_ioloop(io_loop):
'''
A context manager that will set the current ioloop to io_loop for the context
'''
orig_loop = tornado.ioloop.IOLoop.current()
io_loop.make_current()
try:
yield
finally:
orig_loop.make_current() | python | def current_ioloop(io_loop):
'''
A context manager that will set the current ioloop to io_loop for the context
'''
orig_loop = tornado.ioloop.IOLoop.current()
io_loop.make_current()
try:
yield
finally:
orig_loop.make_current() | [
"def",
"current_ioloop",
"(",
"io_loop",
")",
":",
"orig_loop",
"=",
"tornado",
".",
"ioloop",
".",
"IOLoop",
".",
"current",
"(",
")",
"io_loop",
".",
"make_current",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"orig_loop",
".",
"make_current",
"(",
... | A context manager that will set the current ioloop to io_loop for the context | [
"A",
"context",
"manager",
"that",
"will",
"set",
"the",
"current",
"ioloop",
"to",
"io_loop",
"for",
"the",
"context"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/asynchronous.py#L15-L24 | train |
saltstack/salt | salt/modules/saltutil.py | _get_top_file_envs | def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs | python | def _get_top_file_envs():
'''
Get all environments from the top file
'''
try:
return __context__['saltutil._top_file_envs']
except KeyError:
try:
st_ = salt.state.HighState(__opts__,
initial_pillar=__pillar__)
top = st_.get_top()
if top:
envs = list(st_.top_matches(top).keys()) or 'base'
else:
envs = 'base'
except SaltRenderError as exc:
raise CommandExecutionError(
'Unable to render top file(s): {0}'.format(exc)
)
__context__['saltutil._top_file_envs'] = envs
return envs | [
"def",
"_get_top_file_envs",
"(",
")",
":",
"try",
":",
"return",
"__context__",
"[",
"'saltutil._top_file_envs'",
"]",
"except",
"KeyError",
":",
"try",
":",
"st_",
"=",
"salt",
".",
"state",
".",
"HighState",
"(",
"__opts__",
",",
"initial_pillar",
"=",
"_... | Get all environments from the top file | [
"Get",
"all",
"environments",
"from",
"the",
"top",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L78-L98 | train |
saltstack/salt | salt/modules/saltutil.py | _sync | def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret | python | def _sync(form, saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
Sync the given directory in the given environment
'''
if saltenv is None:
saltenv = _get_top_file_envs()
if isinstance(saltenv, six.string_types):
saltenv = saltenv.split(',')
ret, touched = salt.utils.extmods.sync(__opts__, form, saltenv=saltenv, extmod_whitelist=extmod_whitelist,
extmod_blacklist=extmod_blacklist)
# Dest mod_dir is touched? trigger reload if requested
if touched:
mod_file = os.path.join(__opts__['cachedir'], 'module_refresh')
with salt.utils.files.fopen(mod_file, 'a'):
pass
if form == 'grains' and \
__opts__.get('grains_cache') and \
os.path.isfile(os.path.join(__opts__['cachedir'], 'grains.cache.p')):
try:
os.remove(os.path.join(__opts__['cachedir'], 'grains.cache.p'))
except OSError:
log.error('Could not remove grains cache!')
return ret | [
"def",
"_sync",
"(",
"form",
",",
"saltenv",
"=",
"None",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"if",
"saltenv",
"is",
"None",
":",
"saltenv",
"=",
"_get_top_file_envs",
"(",
")",
"if",
"isinstance",
"(",
"... | Sync the given directory in the given environment | [
"Sync",
"the",
"given",
"directory",
"in",
"the",
"given",
"environment"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L101-L123 | train |
saltstack/salt | salt/modules/saltutil.py | update | def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret | python | def update(version=None):
'''
Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3
'''
ret = {}
if not HAS_ESKY:
ret['_error'] = 'Esky not available as import'
return ret
if not getattr(sys, 'frozen', False):
ret['_error'] = 'Minion is not running an Esky build'
return ret
if not __salt__['config.option']('update_url'):
ret['_error'] = '"update_url" not configured on this minion'
return ret
app = esky.Esky(sys.executable, __opts__['update_url'])
oldversion = __grains__['saltversion']
if not version:
try:
version = app.find_update()
except URLError as exc:
ret['_error'] = 'Could not connect to update_url. Error: {0}'.format(exc)
return ret
if not version:
ret['_error'] = 'No updates available'
return ret
try:
app.fetch_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to fetch version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.install_version(version)
except EskyVersionError as exc:
ret['_error'] = 'Unable to install version {0}. Error: {1}'.format(version, exc)
return ret
try:
app.cleanup()
except Exception as exc:
ret['_error'] = 'Unable to cleanup. Error: {0}'.format(exc)
restarted = {}
for service in __opts__['update_restart_services']:
restarted[service] = __salt__['service.restart'](service)
ret['comment'] = 'Updated from {0} to {1}'.format(oldversion, version)
ret['restarted'] = restarted
return ret | [
"def",
"update",
"(",
"version",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"not",
"HAS_ESKY",
":",
"ret",
"[",
"'_error'",
"]",
"=",
"'Esky not available as import'",
"return",
"ret",
"if",
"not",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"... | Update the salt minion from the URL defined in opts['update_url']
SaltStack, Inc provides the latest builds here:
update_url: https://repo.saltstack.com/windows/
Be aware that as of 2014-8-11 there's a bug in esky such that only the
latest version available in the update_url can be downloaded and installed.
This feature requires the minion to be running a bdist_esky build.
The version number is optional and will default to the most recent version
available at opts['update_url'].
Returns details about the transaction upon completion.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.update
salt '*' saltutil.update 0.10.3 | [
"Update",
"the",
"salt",
"minion",
"from",
"the",
"URL",
"defined",
"in",
"opts",
"[",
"update_url",
"]",
"SaltStack",
"Inc",
"provides",
"the",
"latest",
"builds",
"here",
":",
"update_url",
":",
"https",
":",
"//",
"repo",
".",
"saltstack",
".",
"com",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L126-L189 | train |
saltstack/salt | salt/modules/saltutil.py | sync_beacons | def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret | python | def sync_beacons(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev
'''
ret = _sync('beacons', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_beacons()
return ret | [
"def",
"sync_beacons",
"(",
"saltenv",
"=",
"None",
",",
"refresh",
"=",
"True",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"ret",
"=",
"_sync",
"(",
"'beacons'",
",",
"saltenv",
",",
"extmod_whitelist",
",",
"ext... | .. versionadded:: 2015.5.1
Sync beacons from ``salt://_beacons`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for beacons to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available beacons on the minion. This refresh
will be performed even if no new beacons are synced. Set to ``False``
to prevent this refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_beacons
salt '*' saltutil.sync_beacons saltenv=dev
salt '*' saltutil.sync_beacons saltenv=base,dev | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"1"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L192-L228 | train |
saltstack/salt | salt/modules/saltutil.py | sync_sdb | def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret | python | def sync_sdb(saltenv=None, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev
'''
ret = _sync('sdb', saltenv, extmod_whitelist, extmod_blacklist)
return ret | [
"def",
"sync_sdb",
"(",
"saltenv",
"=",
"None",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"ret",
"=",
"_sync",
"(",
"'sdb'",
",",
"saltenv",
",",
"extmod_whitelist",
",",
"extmod_blacklist",
")",
"return",
"ret"
] | .. versionadded:: 2015.5.8,2015.8.3
Sync sdb modules from ``salt://_sdb`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for sdb modules to sync. If no top files
are found, then the ``base`` environment will be synced.
refresh : False
This argument has no affect and is included for consistency with the
other sync functions.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_sdb
salt '*' saltutil.sync_sdb saltenv=dev
salt '*' saltutil.sync_sdb saltenv=base,dev | [
"..",
"versionadded",
"::",
"2015",
".",
"5",
".",
"8",
"2015",
".",
"8",
".",
"3"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L231-L264 | train |
saltstack/salt | salt/modules/saltutil.py | sync_modules | def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret | python | def sync_modules(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev
'''
ret = _sync('modules', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret | [
"def",
"sync_modules",
"(",
"saltenv",
"=",
"None",
",",
"refresh",
"=",
"True",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"ret",
"=",
"_sync",
"(",
"'modules'",
",",
"saltenv",
",",
"extmod_whitelist",
",",
"ext... | .. versionadded:: 0.10.0
Sync execution modules from ``salt://_modules`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for execution modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new execution modules are
synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_modules
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Example:
.. code-block:: bash
salt '*' saltutil.sync_modules
salt '*' saltutil.sync_modules saltenv=dev
salt '*' saltutil.sync_modules saltenv=base,dev | [
"..",
"versionadded",
"::",
"0",
".",
"10",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L267-L320 | train |
saltstack/salt | salt/modules/saltutil.py | refresh_grains | def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True | python | def refresh_grains(**kwargs):
'''
.. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
_refresh_pillar = kwargs.pop('refresh_pillar', True)
if kwargs:
salt.utils.args.invalid_kwargs(kwargs)
# Modules and pillar need to be refreshed in case grains changes affected
# them, and the module refresh process reloads the grains and assigns the
# newly-reloaded grains to each execution module's __grains__ dunder.
refresh_modules()
if _refresh_pillar:
refresh_pillar()
return True | [
"def",
"refresh_grains",
"(",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"_refresh_pillar",
"=",
"kwargs",
".",
"pop",
"(",
"'refresh_pillar'",
",",
"True",
")",
"i... | .. versionadded:: 2016.3.6,2016.11.4,2017.7.0
Refresh the minion's grains without syncing custom grains modules from
``salt://_grains``.
.. note::
The available execution modules will be reloaded as part of this
proceess, as grains can affect which modules are available.
refresh_pillar : True
Set to ``False`` to keep pillar data from being refreshed.
CLI Examples:
.. code-block:: bash
salt '*' saltutil.refresh_grains | [
"..",
"versionadded",
"::",
"2016",
".",
"3",
".",
"6",
"2016",
".",
"11",
".",
"4",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L362-L392 | train |
saltstack/salt | salt/modules/saltutil.py | sync_grains | def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret | python | def sync_grains(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev
'''
ret = _sync('grains', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret | [
"def",
"sync_grains",
"(",
"saltenv",
"=",
"None",
",",
"refresh",
"=",
"True",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"ret",
"=",
"_sync",
"(",
"'grains'",
",",
"saltenv",
",",
"extmod_whitelist",
",",
"extmo... | .. versionadded:: 0.10.0
Sync grains modules from ``salt://_grains`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for grains modules to sync. If no top
files are found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules and recompile
pillar data for the minion. This refresh will be performed even if no
new grains modules are synced. Set to ``False`` to prevent this
refresh.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_grains
salt '*' saltutil.sync_grains saltenv=dev
salt '*' saltutil.sync_grains saltenv=base,dev | [
"..",
"versionadded",
"::",
"0",
".",
"10",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L395-L433 | train |
saltstack/salt | salt/modules/saltutil.py | sync_matchers | def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret | python | def sync_matchers(saltenv=None, refresh=False, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev
'''
ret = _sync('matchers', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
return ret | [
"def",
"sync_matchers",
"(",
"saltenv",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"ret",
"=",
"_sync",
"(",
"'matchers'",
",",
"saltenv",
",",
"extmod_whitelist",
",",
"... | .. versionadded:: 2019.2.0
Sync engine modules from ``salt://_matchers`` to the minion
saltenv
The fileserver environment from which to sync. To sync from more than
one environment, pass a comma-separated list.
If not passed, then all environments configured in the :ref:`top files
<states-top>` will be checked for engines to sync. If no top files are
found, then the ``base`` environment will be synced.
refresh : True
If ``True``, refresh the available execution modules on the minion.
This refresh will be performed even if no new matcher modules are synced.
Set to ``False`` to prevent this refresh.
extmod_whitelist : None
comma-separated list of modules to sync
extmod_blacklist : None
comma-separated list of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_matchers
salt '*' saltutil.sync_matchers saltenv=base,dev | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L553-L588 | train |
saltstack/salt | salt/modules/saltutil.py | list_extmods | def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret | python | def list_extmods():
'''
.. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods
'''
ret = {}
ext_dir = os.path.join(__opts__['cachedir'], 'extmods')
mod_types = os.listdir(ext_dir)
for mod_type in mod_types:
ret[mod_type] = set()
for _, _, files in salt.utils.path.os_walk(os.path.join(ext_dir, mod_type)):
for fh_ in files:
ret[mod_type].add(fh_.split('.')[0])
ret[mod_type] = list(ret[mod_type])
return ret | [
"def",
"list_extmods",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"ext_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'extmods'",
")",
"mod_types",
"=",
"os",
".",
"listdir",
"(",
"ext_dir",
")",
"for",
"mod_type"... | .. versionadded:: 2017.7.0
List Salt modules which have been synced externally
CLI Examples:
.. code-block:: bash
salt '*' saltutil.list_extmods | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L859-L880 | train |
saltstack/salt | salt/modules/saltutil.py | sync_pillar | def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret | python | def sync_pillar(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev
'''
if __opts__['file_client'] != 'local':
raise CommandExecutionError(
'Pillar modules can only be synced to masterless minions'
)
ret = _sync('pillar', saltenv, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret | [
"def",
"sync_pillar",
"(",
"saltenv",
"=",
"None",
",",
"refresh",
"=",
"True",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"if",
"__opts__",
"[",
"'file_client'",
"]",
"!=",
"'local'",
":",
"raise",
"CommandExecutio... | .. versionadded:: 2015.8.11,2016.3.2
Sync pillar modules from the ``salt://_pillar`` directory on the Salt
fileserver. This function is environment-aware, pass the desired
environment to grab the contents of the ``_pillar`` directory from that
environment. The default environment, if none is specified, is ``base``.
refresh : True
Also refresh the execution modules available to the minion, and refresh
pillar data.
extmod_whitelist : None
comma-seperated list of modules to sync
extmod_blacklist : None
comma-seperated list of modules to blacklist based on type
.. note::
This function will raise an error if executed on a traditional (i.e.
not masterless) minion
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_pillar
salt '*' saltutil.sync_pillar saltenv=dev | [
"..",
"versionadded",
"::",
"2015",
".",
"8",
".",
"11",
"2016",
".",
"3",
".",
"2"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L922-L960 | train |
saltstack/salt | salt/modules/saltutil.py | sync_all | def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret | python | def sync_all(saltenv=None, refresh=True, extmod_whitelist=None, extmod_blacklist=None):
'''
.. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']}
'''
log.debug('Syncing all')
ret = {}
ret['clouds'] = sync_clouds(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['beacons'] = sync_beacons(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['modules'] = sync_modules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['states'] = sync_states(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['sdb'] = sync_sdb(saltenv, extmod_whitelist, extmod_blacklist)
ret['grains'] = sync_grains(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['renderers'] = sync_renderers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['returners'] = sync_returners(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['output'] = sync_output(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['utils'] = sync_utils(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['log_handlers'] = sync_log_handlers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['proxymodules'] = sync_proxymodules(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['engines'] = sync_engines(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['thorium'] = sync_thorium(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['serializers'] = sync_serializers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['matchers'] = sync_matchers(saltenv, False, extmod_whitelist, extmod_blacklist)
ret['executors'] = sync_executors(saltenv, False, extmod_whitelist, extmod_blacklist)
if __opts__['file_client'] == 'local':
ret['pillar'] = sync_pillar(saltenv, False, extmod_whitelist, extmod_blacklist)
if refresh:
refresh_modules()
refresh_pillar()
return ret | [
"def",
"sync_all",
"(",
"saltenv",
"=",
"None",
",",
"refresh",
"=",
"True",
",",
"extmod_whitelist",
"=",
"None",
",",
"extmod_blacklist",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Syncing all'",
")",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'cloud... | .. versionchanged:: 2015.8.11,2016.3.2
On masterless minions, pillar modules are now synced, and refreshed
when ``refresh`` is set to ``True``.
Sync down all of the dynamic modules from the file server for a specific
environment. This function synchronizes custom modules, states, beacons,
grains, returners, output modules, renderers, and utils.
refresh : True
Also refresh the execution modules and recompile pillar data available
to the minion. This refresh will be performed even if no new dynamic
modules are synced. Set to ``False`` to prevent this refresh.
.. important::
If this function is executed using a :py:func:`module.run
<salt.states.module.run>` state, the SLS file will not have access to
newly synced execution modules unless a ``refresh`` argument is
added to the state, like so:
.. code-block:: yaml
load_my_custom_module:
module.run:
- name: saltutil.sync_all
- refresh: True
See :ref:`here <reloading-modules>` for a more detailed explanation of
why this is necessary.
extmod_whitelist : None
dictionary of modules to sync based on type
extmod_blacklist : None
dictionary of modules to blacklist based on type
CLI Examples:
.. code-block:: bash
salt '*' saltutil.sync_all
salt '*' saltutil.sync_all saltenv=dev
salt '*' saltutil.sync_all saltenv=base,dev
salt '*' saltutil.sync_all extmod_whitelist={'modules': ['custom_module']} | [
"..",
"versionchanged",
"::",
"2015",
".",
"8",
".",
"11",
"2016",
".",
"3",
".",
"2",
"On",
"masterless",
"minions",
"pillar",
"modules",
"are",
"now",
"synced",
"and",
"refreshed",
"when",
"refresh",
"is",
"set",
"to",
"True",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/saltutil.py#L963-L1034 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.