Use minutes to set

Add ability to use test=True on the state
More documentation improvements
Add log messages
This commit is contained in:
twangboy 2018-06-26 16:54:42 -06:00
parent 7dc7eb11c2
commit b20453de9f
No known key found for this signature in database
GPG key ID: 93FF3BDEB278C9EB
2 changed files with 233 additions and 139 deletions

View file

@ -7,52 +7,55 @@ powercfg.
.. code-block:: bash
# Set monitor to never turn off
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes
salt '*' powercfg.set_disk_timeout 7200 power=ac
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import
import re
import logging
# Import Salt Libs
import salt.utils
log = logging.getLogger(__name__)
__virtualname__ = "powercfg"
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if __grains__['os'] == 'Windows':
return __virtualname__
return (False, 'Module only works on Windows.')
if not salt.utils.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = "powercfg /getactivescheme"
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r"GUID: (.*) \(", out)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an array for a guid and subguid for a the given scheme
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = "powercfg /q {0} {1}".format(scheme, guid)
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = "powercfg /q {0} {1} {2}".format(scheme, guid, subguid)
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split("\r\n\r\n")
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
@ -61,42 +64,49 @@ def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
else:
out = split[0]
raw_settings = re.findall(r"Power Setting Index: ([0-9a-fx]+)", out)
return {"ac": int(raw_settings[0], 0) / 60, "dc": int(raw_settings[1], 0) / 60}
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the value of a setting with a given power (ac/dc) to
the given scheme
Sets the AC/DC values of a setting with the given power for the given scheme
'''
if scheme is None:
scheme = _get_current_scheme()
cmd = "powercfg /set{0}valueindex {1} {2} {3} {4}".format(power, scheme, sub_group, setting_guid, value)
return __salt__['cmd.run'](cmd, python_shell=False)
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def set_monitor_timeout(timeout, power="ac", scheme=None):
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in seconds for the given power scheme
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in seconds before the monitor will timeout
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC (battery). Valid options are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
Default is ``ac``
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
str: The stdout of the powercfg command
bool: ``True`` if successful, otherwise ``False``
CLI Example:
@ -107,8 +117,8 @@ def set_monitor_timeout(timeout, power="ac", scheme=None):
'''
return _set_powercfg_value(
scheme=scheme,
sub_group="SUB_VIDEO",
setting_guid="VIDEOIDLE",
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
@ -119,8 +129,13 @@ def get_monitor_timeout(scheme=None):
Args:
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
@ -133,31 +148,37 @@ def get_monitor_timeout(scheme=None):
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid="SUB_VIDEO",
subguid="VIDEOIDLE",
safe_name="Turn off display after")
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def set_disk_timeout(timeout, power="ac", scheme=None):
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in seconds for the given power scheme
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in seconds before the disk will timeout
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC (battery). Valid options are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
Default is ``ac``
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
str: The stdout of the powercfg command
bool: ``True`` if successful, otherwise ``False``
CLI Example:
@ -168,8 +189,8 @@ def set_disk_timeout(timeout, power="ac", scheme=None):
'''
return _set_powercfg_value(
scheme=scheme,
sub_group="SUB_DISK",
setting_guid="DISKIDLE",
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
@ -180,8 +201,13 @@ def get_disk_timeout(scheme=None):
Args:
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
@ -194,31 +220,37 @@ def get_disk_timeout(scheme=None):
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid="SUB_DISK",
subguid="DISKIDLE",
safe_name="Turn off hard disk after")
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def set_standby_timeout(timeout, power="ac", scheme=None):
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in seconds for the given power scheme
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in seconds before the computer sleeps
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC (battery). Valid options are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
Default is ``ac``
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
str: The stdout of the powercfg command
bool: ``True`` if successful, otherwise ``False``
CLI Example:
@ -229,8 +261,8 @@ def set_standby_timeout(timeout, power="ac", scheme=None):
'''
return _set_powercfg_value(
scheme=scheme,
sub_group="SUB_SLEEP",
setting_guid="STANDBYIDLE",
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
@ -239,10 +271,14 @@ def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
@ -255,31 +291,37 @@ def get_standby_timeout(scheme=None):
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid="SUB_SLEEP",
subguid="STANDBYIDLE",
safe_name="Sleep after")
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def set_hibernate_timeout(timeout, power="ac", scheme=None):
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in seconds for the given power scheme
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in seconds before the computer hibernates
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC (battery). Valid options are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
Default is ``ac``
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
str: The stdout of the powercfg command
bool: ``True`` if successful, otherwise ``False``
CLI Example:
@ -290,8 +332,8 @@ def set_hibernate_timeout(timeout, power="ac", scheme=None):
'''
return _set_powercfg_value(
scheme=scheme,
sub_group="SUB_SLEEP",
setting_guid="HIBERNATEIDLE",
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
@ -300,10 +342,14 @@ def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as None to use the current. Default is
``None``
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
@ -316,6 +362,6 @@ def get_hibernate_timeout(scheme=None):
'''
return _get_powercfg_minute_values(
scheme=scheme,
guid="SUB_SLEEP",
subguid="HIBERNATEIDLE",
safe_name="Hibernate after")
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')

View file

@ -8,6 +8,7 @@ powercfg.
.. code-block:: yaml
# Set timeout to 30 minutes on battery power
monitor:
powercfg.set_timeout:
- value: 30
@ -18,82 +19,129 @@ powercfg.
from __future__ import absolute_import
import logging
# Import Salt Libs
import salt.utils
log = logging.getLogger(__name__)
__virtualname__ = "powercfg"
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if __grains__['os'] == 'Windows':
return __virtualname__
return False
if not salt.utils.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _check_or_set(check_func, set_func, value, power):
values = check_func()
if values[power] == value:
return True
else:
set_func(value, power)
return False
def set_timeout(name, value, power="ac", scheme=None):
def set_timeout(name, value, power='ac', scheme=None):
'''
Set the sleep timeouts of specific items such as disk, monitor.
Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
- ``hibernate``
value (int):
The amount of time in minutes before the item will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
CLI Example:
.. code-block:: yaml
# Set monitor timeout to 30 minutes on Battery
monitor:
powercfg.set_timeout:
- value: 30
- power: dc
powercfg.set_timeout:
- value: 30
- power: dc
# Set disk timeout to 10 minutes on AC Power
disk:
powercfg.set_timeout:
- value: 12
- power: ac
name
The setting to change, can be one of the following: monitor, disk, standby, hibernate
timeout
The amount of time in minutes before the item will timeout i.e the monitor
power
Should we set the value for AC or DC (battery)? Valid options ac,dc.
scheme
The scheme to use, leave as None to use the current.
powercfg.set_timeout:
- value: 10
- power: ac
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
comment = []
# Validate name values
name = name.lower()
if name not in ['monitor', 'disk', 'standby', 'hibernate']:
ret['result'] = False
ret['comment'] = '"{0}" is not a valid setting'.format(name)
log.debug(ret['comment'])
return ret
if name not in ["monitor", "disk", "standby", "hibernate"]:
ret["result"] = False
comment.append("{0} is not a valid setting".format(name))
elif power not in ["ac", "dc"]:
ret["result"] = False
comment.append("{0} is not a power type".format(power))
# Validate power values
power = power.lower()
if power not in ['ac', 'dc']:
ret['result'] = False
ret['comment'] = '"{0}" is not a power type'.format(power)
log.debug(ret['comment'])
return ret
# Get current settings
old = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme)
# Check current settings
if old[power] == value:
ret['comment'] = '{0} timeout on {1} power is already set to {2}' \
''.format(name.capitalize(), power.upper(), value)
return ret
else:
check_func = __salt__["powercfg.get_{0}_timeout".format(name)]
set_func = __salt__["powercfg.set_{0}_timeout".format(name)]
ret['comment'] = '{0} timeout on {1} power will be set to {2}' \
''.format(name.capitalize(), power.upper(), value)
values = check_func(scheme=scheme)
if values[power] == value:
comment.append("{0} {1} is already set with the value {2}.".format(name, power, value))
else:
ret['changes'] = {name: {power: value}}
set_func(value, power, scheme=scheme)
# Check for test=True
if __opts__['test']:
ret['result'] = None
return ret
# Set the timeout value
__salt__['powercfg.set_{0}_timeout'.format(name)](
timeout=value,
power=power,
scheme=scheme)
# Get the setting after the change
new = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme)
changes = salt.utils.compare_dicts(old, new)
if changes:
ret['changes'] = {name: changes}
ret['comment'] = '{0} timeout on {1} power set to {2}' \
''.format(name.capitalize(), power.upper(), value)
else:
ret['changes'] = {}
ret['comment'] = 'Failed to set {0} timeout on {1} power to {2}' \
''.format(name, power.upper(), value)
ret['result'] = False
ret['comment'] = ' '.join(comment)
return ret