pax_global_header 0000666 0000000 0000000 00000000064 13206577772 0014532 g ustar 00root root 0000000 0000000 52 comment=9ba7cf8b7b3b08ccfb314435127c7c4b70b20a8e
autosuspend-1.0.0/ 0000775 0000000 0000000 00000000000 13206577772 0014102 5 ustar 00root root 0000000 0000000 autosuspend-1.0.0/.coveragerc 0000664 0000000 0000000 00000000213 13206577772 0016217 0 ustar 00root root 0000000 0000000 [run]
branch = True
[report]
exclude_lines =
pragma: no cover
def __repr__
if __name__ == "__main__":
@abc.abstractmethod
autosuspend-1.0.0/.gitignore 0000664 0000000 0000000 00000000136 13206577772 0016072 0 ustar 00root root 0000000 0000000 /.cache
/.coverage
*.egg-info
/.eggs
/build
/dist
/htmlcov
/tags
__pycache__
/pytestdebug.log
autosuspend-1.0.0/.travis.yml 0000664 0000000 0000000 00000000566 13206577772 0016222 0 ustar 00root root 0000000 0000000 language: python
sudo: false
env:
- PSUTIL_VERSION=5.0.1
- PSUTIL_VERSION=5.4.1
python:
- "3.5"
- "3.6"
- "nightly"
install:
- pip install pytest pytest-runner pytest-cov pytest-mock python-mpd2 psutil==$PSUTIL_VERSION requests codecov lxml sphinx sphinx_rtd_theme
script:
- pytest --cov=autosuspend
- python setup.py build_sphinx
after_success:
- codecov
autosuspend-1.0.0/LICENSE.txt 0000664 0000000 0000000 00000035562 13206577772 0015740 0 ustar 00root root 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
autosuspend-1.0.0/README.md 0000664 0000000 0000000 00000001537 13206577772 0015367 0 ustar 00root root 0000000 0000000 # autosuspend
[](https://travis-ci.org/languitar/autosuspend) [](https://codecov.io/gh/languitar/autosuspend) [](http://autosuspend.readthedocs.io/en/latest/?badge=latest)
`autosuspend` is a python daemon that suspends a system if certain conditions are met, or not met. This enables a server to sleep in case of inactivity without depending on the X infrastructure usually used by normal desktop environments.
Documentation is [available here](https://autosuspend.readthedocs.io).
## License
This software is licensed using the [GPL2 license](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html).
autosuspend-1.0.0/VERSION 0000664 0000000 0000000 00000000012 13206577772 0015143 0 ustar 00root root 0000000 0000000 1.0
1.0.0
autosuspend-1.0.0/autosuspend 0000775 0000000 0000000 00000061024 13206577772 0016405 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import abc
import argparse
import configparser
import copy
import functools
import glob
import logging
import logging.config
import os
import pwd
import re
import socket
import subprocess
import sys
import time
import psutil
# pylint: disable=invalid-name
_logger = logging.getLogger()
# pylint: enable=invalid-name
class ConfigurationError(RuntimeError):
"""
Indicates an error in the configuration of a :class:`Check`.
"""
pass
class TemporaryCheckError(RuntimeError):
"""
Indicates a temporary error while performing a check which can be ignored
for some time since it might recover automatically.
"""
pass
class SevereCheckError(RuntimeError):
"""
Indicates that a check cannot be executed correctly and there is no hope
this situation recovers.
"""
pass
class Check(object):
"""
Base class for checks.
Subclasses must call this class' __init__ method.
"""
@classmethod
@abc.abstractmethod
def create(cls, name, config):
"""
Factory method to create an appropriate instance of the check for the
provided options.
Args:
name (str):
user-defined name for the check
config (configparser.SectionProxy):
config parser section with the configuration for this check
Raises:
ConfigurationError:
Configuration for this check is inappropriate
"""
pass
def __init__(self, name=None):
if name:
self.name = name
else:
self.name = self.__class__.__name__
self.logger = logging.getLogger(
'check.{}'.format(self.name))
@abc.abstractmethod
def check(self):
"""
Performs a check and reports whether suspending shall NOT take place.
Returns:
str:
A string describing which condition currently prevents sleep,
else ``None``.
Raises:
TemporaryCheckError:
Check execution currently fails but might recover later
SevereCheckError:
Check executions fails severely
"""
pass
def __str__(self):
return '{name}[class={clazz}]'.format(name=self.name,
clazz=self.__class__.__name__)
class Ping(Check):
"""
Prevents system sleep in case one or several hosts are reachable via ping.
"""
@classmethod
def create(cls, name, config):
try:
hosts = config['hosts'].split(',')
hosts = [h.strip() for h in hosts]
return cls(name, hosts)
except KeyError as error:
raise ConfigurationError(
'Unable to determine hosts to ping: {}'.format(error))
def __init__(self, name, hosts):
Check.__init__(self, name)
self._hosts = hosts
def check(self):
for host in self._hosts:
cmd = ['ping', '-q', '-c', '1', host]
if subprocess.call(cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL) == 0:
self.logger.debug("host " + host + " appears to be up")
return 'Host {} is up'.format(host)
return None
class Mpd(Check):
@classmethod
def create(cls, name, config):
try:
host = config.get('host', fallback='localhost')
port = config.getint('port', fallback=6600)
timeout = config.getint('timeout', fallback=5)
return cls(name, host, port, timeout)
except ValueError as error:
raise ConfigurationError(
'Host port or timeout configuration wrong: {}'.format(error))
def __init__(self, name, host, port, timeout):
Check.__init__(self, name)
self._host = host
self._port = port
self._timeout = timeout
def _get_state(self):
from mpd import MPDClient
client = MPDClient()
client.timeout = self._timeout
client.connect(self._host, self._port)
state = client.status()
client.close()
client.disconnect()
return state
def check(self):
try:
state = self._get_state()
if state['state'] == 'play':
return 'MPD currently playing'
else:
return None
except (ConnectionError,
ConnectionRefusedError,
socket.timeout,
socket.gaierror) as error:
raise TemporaryCheckError(error)
class Kodi(Check):
@classmethod
def create(cls, name, config):
try:
url = config.get('url', fallback='http://localhost:8080/jsonrpc')
timeout = config.getint('timeout', fallback=5)
return cls(name, url, timeout)
except ValueError as error:
raise ConfigurationError(
'Url or timeout configuration wrong: {}'.format(error))
def __init__(self, name, url, timeout):
Check.__init__(self, name)
self._url = url
self._timeout = timeout
def check(self):
import requests
import requests.exceptions
try:
reply = requests.get(self._url +
'?request={"jsonrpc": "2.0", '
'"id": 1, '
'"method": "Player.GetActivePlayers"}').json()
if 'result' not in reply:
raise TemporaryCheckError('No result array in reply')
if reply['result']:
return "Kodi currently playing"
else:
return None
except requests.exceptions.RequestException as error:
raise TemporaryCheckError(error)
class Users(Check):
@classmethod
def create(cls, name, config):
try:
user_regex = re.compile(
config.get('name', fallback='.*'))
terminal_regex = re.compile(
config.get('terminal', fallback='.*'))
host_regex = re.compile(
config.get('host', fallback='.*'))
return cls(name, user_regex, terminal_regex, host_regex)
except re.error as error:
raise ConfigurationError(
'Regular expression is invalid: {}'.format(error))
def __init__(self, name, user_regex, terminal_regex, host_regex):
Check.__init__(self, name)
self._user_regex = user_regex
self._terminal_regex = terminal_regex
self._host_regex = host_regex
def check(self):
for entry in psutil.users():
if self._user_regex.fullmatch(entry.name) is not None and \
self._terminal_regex.fullmatch(
entry.terminal) is not None and \
self._host_regex.fullmatch(entry.host) is not None:
self.logger.debug('User %s on terminal %s from host %s '
'matches criteria.', entry.name,
entry.terminal, entry.host)
return 'User {user} is logged in on terminal {terminal} ' \
'from {host} since {started}'.format(
user=entry.name, terminal=entry.terminal,
host=entry.host, started=entry.started)
return None
class Smb(Check):
@classmethod
def create(cls, name, config):
return cls(name)
def check(self):
try:
status_output = subprocess.check_output(
['smbstatus', '-b']).decode('utf-8')
except subprocess.CalledProcessError as error:
raise SevereCheckError(error)
self.logger.debug('Received status output:\n%s',
status_output)
connections = []
start_seen = False
for line in status_output.splitlines():
if start_seen:
connections.append(line)
else:
if line.startswith('----'):
start_seen = True
if connections:
return 'SMB clients are connected:\n{}'.format(
'\n'.join(connections))
else:
return None
class Processes(Check):
@classmethod
def create(cls, name, config):
try:
processes = config['processes'].split(',')
processes = [p.strip() for p in processes]
return cls(name, processes)
except KeyError:
raise ConfigurationError('No processes to check specified')
def __init__(self, name, processes):
Check.__init__(self, name)
self._processes = processes
def check(self):
for proc in psutil.process_iter():
try:
pinfo = proc.name()
for name in self._processes:
if pinfo == name:
return 'Process {} is running'.format(name)
except psutil.NoSuchProcess:
pass
return None
class ActiveConnection(Check):
@classmethod
def create(cls, name, config):
try:
ports = config['ports']
ports = ports.split(',')
ports = [p.strip() for p in ports]
ports = set([int(p) for p in ports])
return cls(name, ports)
except KeyError:
raise ConfigurationError('Missing option ports')
except ValueError:
raise ConfigurationError('Ports must be integers')
def __init__(self, name, ports):
Check.__init__(self, name)
self._ports = ports
def check(self):
own_addresses = [(item.family, item.address)
for sublist in psutil.net_if_addrs().values()
for item in sublist]
connected = [c.laddr[1]
for c in psutil.net_connections()
if ((c.family, c.laddr[0]) in own_addresses
and c.status == 'ESTABLISHED'
and c.laddr[1] in self._ports)]
if connected:
return 'Ports {} are connected'.format(connected)
class Load(Check):
@classmethod
def create(cls, name, config):
try:
return cls(name,
config.getfloat('threshold', fallback=2.5))
except ValueError as error:
raise ConfigurationError(
'Unable to parse threshold as float: {}'.format(error))
def __init__(self, name, threshold):
Check.__init__(self, name)
self._threshold = threshold
def check(self):
loadcurrent = os.getloadavg()[1]
self.logger.debug("Load: %s", loadcurrent)
if loadcurrent > self._threshold:
return 'Load {} > threshold {}'.format(loadcurrent,
self._threshold)
else:
return None
class XIdleTime(Check):
'''
Checks users with a local X display have been idle for a sufficiently long
time.
'''
@classmethod
def create(cls, name, config):
try:
return cls(name, config.getint('timeout', fallback=600),
re.compile(config.get('ignore_if_process',
fallback=r'a^')),
re.compile(config.get('ignore_users',
fallback=r'^a')))
except re.error as error:
raise ConfigurationError(
'Regular expression is invalid: {}'.format(error))
except ValueError as error:
raise ConfigurationError(
'Unable to parse timeout as int: {}'.format(error))
def __init__(self, name, timeout, ignore_process_re, ignore_users_re):
Check.__init__(self, name)
self._timeout = timeout
self._ignore_process_re = ignore_process_re
self._ignore_users_re = ignore_users_re
def check(self):
sockets = glob.glob('/tmp/.X11-unix/X*')
self.logger.debug('Found sockets: %s', sockets)
for sock in sockets:
self.logger.info('Checking socket %s', sock)
# determine the number of the X display
try:
number = int(sock[len('/tmp/.X11-unix/X'):])
except ValueError as error:
self.logger.warning(
'Cannot parse display number from socket %s. Skipping.',
sock, exc_info=True)
continue
# determine the user of the display
try:
user = pwd.getpwuid(os.stat(sock).st_uid).pw_name
except (FileNotFoundError, KeyError) as error:
self.logger.warning(
'Cannot get the owning user from socket %s. Skipping.',
sock, exc_info=True)
continue
# check whether this users should be ignored completely
if self._ignore_users_re.match(user) is not None:
self.logger.debug("Skipping user '%s' due to request", user)
continue
# check whether any of the running processes of this user matches
# the ignore regular expression. In that case we skip ideltime
# checking because we assume the user has a process running, which
# inevitably tampers with the idle time.
user_processes = []
for process in psutil.process_iter():
try:
if process.username() == user:
user_processes.append(process.name())
except (psutil.NoSuchProcess,
psutil.ZombieProcess,
psutil.AccessDenied):
# ignore processes which have disappeared etc.
pass
skip = False
for process in user_processes:
if self._ignore_process_re.match(process) is not None:
self.logger.debug(
"Process %s with pid %s matches the ignore regex '%s'."
" Skipping idle time check for this user.",
process.name(), process.pid, self._ignore_process_re)
skip = True
break
if skip:
continue
# prepare the environment for the xprintidle call
env = copy.deepcopy(os.environ)
env['DISPLAY'] = ':{}'.format(number)
try:
idle_time = subprocess.check_output(
['sudo', '-u', user, 'xprintidle'], env=env)
idle_time = float(idle_time.strip()) / 1000.0
except (subprocess.CalledProcessError, ValueError) as error:
self.logger.warning(
'Unable to determine the idle time for display %s.',
number, exc_info=True)
raise TemporaryCheckError(error)
self.logger.debug(
'Idle time for display %s of user %s is %s seconds.',
number, user, idle_time)
if idle_time < self._timeout:
return 'X session {} of user {} ' \
'has idle time {} < threshold {}'.format(
number, user, idle_time, self._timeout)
return None
class ExternalCommand(Check):
@classmethod
def create(cls, name, config):
try:
return cls(name, config['command'].strip())
except KeyError as error:
raise ConfigurationError('Missing command specification')
def __init__(self, name, command):
Check.__init__(self, name)
self._command = command
def check(self):
try:
subprocess.check_call(self._command, shell=True)
return 'Command {} succeeded'.format(self._command)
except subprocess.CalledProcessError as error:
return None
class XPath(Check):
@classmethod
def create(cls, name, config):
from lxml import etree
try:
xpath = config['xpath'].strip()
# validate the expression
try:
etree.fromstring('').xpath(xpath)
except etree.XPathEvalError:
raise ConfigurationError('Invalid xpath expression: ' + xpath)
return cls(name, xpath, config['url'])
except KeyError as error:
raise ConfigurationError('No ' + str(error) +
' entry defined for the XPath check')
def __init__(self, name, xpath, url):
Check.__init__(self, name)
self._xpath = xpath
self._url = url
def check(self):
import requests
import requests.exceptions
from lxml import etree
try:
reply = requests.get(self._url).text
root = etree.fromstring(reply)
if root.xpath(self._xpath):
return "XPath matches for url " + self._url
except requests.exceptions.RequestException as error:
raise TemporaryCheckError(error)
except etree.XMLSyntaxError as error:
raise TemporaryCheckError(error)
def execute_suspend(command):
_logger.info('Suspending using command: %s', command)
try:
subprocess.check_call(command, shell=True)
except subprocess.CalledProcessError:
_logger.warning('Unable to execute suspend command: %s', command,
exc_info=True)
# pylint: disable=invalid-name
_checks = []
# pylint: enable=invalid-name
JUST_WOKE_UP_FILE = '/tmp/autosuspend-just-woke-up'
def execute_checks(checks, all_checks, logger):
matched = False
for check in checks:
logger.debug('Executing check %s', check.name)
try:
result = check.check()
if result is not None:
logger.info('Check %s matched. Reason: %s', check.name, result)
matched = True
if not all_checks:
logger.debug('Skipping further checks')
break
except TemporaryCheckError:
logger.warning('Check %s failed. Ignoring...', check,
exc_info=True)
return matched
def loop(interval, idle_time, sleep_fn, all_checks=False, run_for=None):
logger = logging.getLogger('loop')
start_time = time.time()
idle_since = None
while (run_for is None) or (time.time() < (start_time + run_for)):
logger.info('Starting new check iteration')
matched = execute_checks(_checks, all_checks, logger)
logger.debug('All checks have been executed')
if os.path.isfile(JUST_WOKE_UP_FILE):
logger.info('Just woke up from suspension. Resetting')
os.remove(JUST_WOKE_UP_FILE)
idle_since = None
time.sleep(interval)
elif matched:
logger.info('Check iteration finished. System is active. '
'Sleeping until next iteration')
idle_since = None
time.sleep(interval)
else:
if idle_since is None:
idle_since = time.time()
logger.info('No checks matched. System is idle since %s',
idle_since)
if time.time() - idle_since > idle_time:
logger.info('System is idle long enough. Suspending...')
sleep_fn()
idle_since = None
else:
logger.info('Desired idle time of %s secs not reached so far. '
'Continuing checks', idle_time)
time.sleep(interval)
def set_up_checks(config):
configured_checks = []
check_section = [s for s in config.sections() if s.startswith('check.')]
for section in check_section:
name = section[len('check.'):]
# legacy method to determine the check name from the section header
class_name = name
# if there is an explicit class, use that one with higher priority
if 'class' in config[section]:
class_name = config[section]['class']
enabled = config.getboolean(section, 'enabled', fallback=False)
if not enabled:
_logger.debug('Skipping disabled check {}'.format(name))
continue
_logger.info('Configuring check {} with class {}'.format(
name, class_name))
try:
klass = globals()[class_name]
except KeyError:
raise ConfigurationError(
'Cannot create check named {}: Class does not exist'.format(
class_name))
check = klass.create(name, config[section])
if not isinstance(check, Check):
raise ConfigurationError(
'Check {} is not a correct Check instance'.format(check))
_logger.debug('Created check instance {}'.format(check))
configured_checks.append(check)
if not configured_checks:
raise ConfigurationError('No checks enabled')
return configured_checks
def parse_config(config_file):
_logger.debug('Reading config file %s', config_file)
config = configparser.ConfigParser()
config.read_file(config_file)
_logger.debug('Parsed config file: %s', config)
return config
def parse_arguments(args):
parser = argparse.ArgumentParser(
description='Automatically suspends a server '
'based on several criteria',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
try:
default_config = open('/etc/autosuspend.conf', 'r')
except (FileNotFoundError, IsADirectoryError, PermissionError):
default_config = None
parser.add_argument(
'-c', '--config',
dest='config_file',
type=argparse.FileType('r'),
default=default_config,
required=default_config is None,
metavar='FILE',
help='The config file to use')
parser.add_argument(
'-a', '--allchecks',
dest='all_checks',
default=False,
action='store_true',
help='Execute all checks even if one has already prevented '
'the system from going to sleep. Useful to debug individual '
'checks.')
parser.add_argument(
'-r', '--runfor',
dest='run_for',
type=float,
default=None,
metavar='SEC',
help="If set, run for the specified amount of seconds before exiting "
"instead of endless execution.")
parser.add_argument(
'-l', '--logging',
type=argparse.FileType('r'),
nargs='?',
default=False,
const=True,
metavar='FILE',
help='Configures the python logging system. If used '
'without an argument, all logging is enabled to '
'the console. If used with an argument, the '
'configuration is read from the specified file.')
args = parser.parse_args(args)
_logger.debug('Parsed command line arguments %s', args)
return args
def configure_logging(file_or_flag):
"""
Configure the python :mod:`logging` system.
If the provided argument is a `file` instance, try to use the
pointed to file as a configuration for the logging system. Otherwise,
if the given argument evaluates to :class:True:, use a default
configuration with many logging messages. If everything fails, just log
starting from the warning level.
Args:
file_or_flag (file or bool):
either a configuration file pointed by a :ref:`file object
` instance or something that evaluates
to :class:`bool`.
"""
if isinstance(file_or_flag, bool):
if file_or_flag:
logging.basicConfig(level=logging.DEBUG)
else:
# at least configure warnings
logging.basicConfig(level=logging.WARNING)
else:
try:
logging.config.fileConfig(file_or_flag)
except Exception as error:
# at least configure warnings
logging.basicConfig(level=logging.WARNING)
_logger.warning('Unable to configure logging from file %s. '
'Falling back to warning level.',
file_or_flag,
exc_info=True)
def main(args=None):
global _checks
args = parse_arguments(args)
configure_logging(args.logging)
config = parse_config(args.config_file)
_checks = set_up_checks(config)
loop(config.getfloat('general', 'interval', fallback=60),
config.getfloat('general', 'idle_time', fallback=300),
functools.partial(execute_suspend,
config.get('general', 'suspend_cmd')),
all_checks=args.all_checks,
run_for=args.run_for)
if __name__ == "__main__":
main()
autosuspend-1.0.0/autosuspend-detect-suspend.service 0000664 0000000 0000000 00000000274 13206577772 0022766 0 ustar 00root root 0000000 0000000 [Unit]
Description=Notifies autosuspend about suspension
Before=sleep.target
[Service]
Type=simple
ExecStart=/usr/bin/touch /tmp/autosuspend-just-woke-up
[Install]
WantedBy=sleep.target
autosuspend-1.0.0/autosuspend-logging.conf 0000664 0000000 0000000 00000000772 13206577772 0020755 0 ustar 00root root 0000000 0000000 [loggers]
keys=root,loop,checks
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=INFO
handlers=consoleHandler
[logger_checks]
qualname=check
propagate=0
level=INFO
handlers=consoleHandler
[logger_loop]
qualname=loop
propagate=0
level=DEBUG
handlers=consoleHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
autosuspend-1.0.0/autosuspend.conf 0000664 0000000 0000000 00000001512 13206577772 0017322 0 ustar 00root root 0000000 0000000 [general]
interval = 30
idle_time = 900
suspend_cmd = /usr/bin/systemctl suspend
[check.Ping]
enabled = false
hosts = 192.168.0.7
[check.RemoteUsers]
class = Users
enabled = true
name = .*
terminal = .*
host = [0-9].*
[check.LocalUsers]
class = Users
enabled = false
name = .*
terminal = .*
host = localhost
[check.Smb]
enabled = false
[check.Nfs]
enabled = false
[check.Processes]
enabled = true
processes = rsync,rdiff-backup
[check.Mpd]
enabled = true
timeout = 2
[check.Kodi]
enabled = true
timeout = 2
[check.ActiveConnection]
enabled = true
ports = 22,445,139
[check.Load]
enabled = true
threshold = 2.5
[check.XIdleTime]
enabled = true
timeout = 360
[check.Tvheadend]
class = XPath
enabled = false
url = http://localhost:9981/status.xml
xpath = /currentload/subscriptions[number(.) > 0] | /currentload/recordings/recording
autosuspend-1.0.0/autosuspend.py 0000777 0000000 0000000 00000000000 13206577772 0021316 2autosuspend ustar 00root root 0000000 0000000 autosuspend-1.0.0/autosuspend.service 0000664 0000000 0000000 00000000317 13206577772 0020037 0 ustar 00root root 0000000 0000000 [Unit]
Description=A daemon to suspend your server in case of inactivity
After=network.target
[Service]
ExecStart=/usr/bin/autosuspend -l /etc/autosuspend-logging.conf
[Install]
WantedBy=multi-user.target
autosuspend-1.0.0/doc/ 0000775 0000000 0000000 00000000000 13206577772 0014647 5 ustar 00root root 0000000 0000000 autosuspend-1.0.0/doc/source/ 0000775 0000000 0000000 00000000000 13206577772 0016147 5 ustar 00root root 0000000 0000000 autosuspend-1.0.0/doc/source/available_checks.inc 0000664 0000000 0000000 00000007127 13206577772 0022111 0 ustar 00root root 0000000 0000000 Available checks
----------------
The following checks for activity are currently implemented.
Each of the is described with its available configuration options and required optional dependencies.
Ping
~~~~
.. program:: check-ping
Checks whether one or more hosts answer to ICMP requests.
Options
^^^^^^^
.. option:: hosts
Comma-separated list of host names or IPs.
Requirements
^^^^^^^^^^^^
Mpd
~~~
.. program:: check-mpd
Checks whether an instance of `MPD`_ is currently playing music.
Options
^^^^^^^
.. option:: host
Host containing the MPD daemon, default: ``localhost``
.. option:: port
Port to connect to the MPD daemon, default: ``6600``
.. option:: timeout
.. _mpd-timeout:
Request timeout in seconds, default: ``5``
Requirements
^^^^^^^^^^^^
- `python-mpd2`_
Kodi
~~~~
.. program:: check-kodi
Checks whether an instance of `Kodi`_ is currently playing.
Options
^^^^^^^
.. option:: url
Base URL of the JSON RPC API of the Kodi instance, default: ``http://localhost:8080/jsonrpc``
.. option:: timeout
Request timeout in seconds, default: ``5``
Requirements
^^^^^^^^^^^^
- `requests`_
Users
~~~~~
.. program:: check-users
Checks whether a user currently logged in at the system matches several criteria.
All provided criteria must match to indicate activity on the host.
Options
^^^^^^^
All regular expressions are applied against the full string.
Capturing substrings needs to be explicitly enabled using wildcard matching.
.. option:: name
A regular expression specifying which users to capture, default: ``.*``.
.. option:: terminal
A regular expression specifying the terminal on which the user needs to be logged in, default: ``.*``.
.. option:: host
A regular expression specifying the host from which a user needs to be logged in, default: ``.*``.
Requirements
^^^^^^^^^^^^
Smb
~~~
.. program:: check-smb
Any active Samba connection will block suspend.
Options
^^^^^^^
Requirements
^^^^^^^^^^^^
.. option:: smbstatus
executable needs to be present.
Processes
~~~~~~~~~
.. program:: check-processes
If currently running processes match an expression, the suspend will be blocked.
You might use this to hinder the system from suspending when for example your rsync runs.
Options
^^^^^^^
.. option:: processes
list of comma-separated process names to check for
Requirements
^^^^^^^^^^^^
ActiveConnection
~~~~~~~~~~~~~~~~
.. program:: check-active-connections
Checks whether there is currently a client connected to a TCP server at certain ports.
Can be used to e.g. block suspending the system in case SSH users are connected or a web server is used by clients.
Options
^^^^^^^
.. option:: ports
list of comma-separated port numbers
Requirements
^^^^^^^^^^^^
Load
~~~~
.. program:: check-load
Checks whether the system load 5 is below a certain value.
Options
^^^^^^^
.. option:: threshold
a float for the maximum allowed load value, default: 2.5
Requirements
^^^^^^^^^^^^
XIdleTime
~~~~~~~~~
.. program:: check-xidletime
Checks whether all active local X displays have been idle for a sufficiently long time.
This assumes a recent operating system where the X server is started with user permissions (i.e. not as root).
Options
^^^^^^^
.. option:: timeout
required idle time in seconds
.. option:: ignore_if_process
a regular expression to match against the process names executed by each X session owner.
In case the use has a process running, which matches against this expression, the X idle time is ignore and the check continues as if there was no activity.
This can be useful in case of processes which inevitabl
autosuspend-1.0.0/doc/source/available_checks.rst 0000664 0000000 0000000 00000000071 13206577772 0022137 0 ustar 00root root 0000000 0000000 .. _available-checks:
.. include:: available_checks.inc
autosuspend-1.0.0/doc/source/conf.py 0000664 0000000 0000000 00000004062 13206577772 0017450 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import os.path
# needs_sphinx = '1.0'
extensions = ['sphinx.ext.intersphinx']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'autosuspend'
copyright = '2017, Johannes Wienke'
author = 'Johannes Wienke'
with open(os.path.join(
os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
'../..',
'VERSION'), 'r') as version_file:
lines = version_file.readlines()
version = lines[0].strip()
release = lines[1].strip()
language = None
exclude_patterns = []
pygments_style = 'sphinx'
todo_include_todos = False
rst_epilog = '''
.. _autosuspend: https://github.com/languitar/autosuspend
.. _Python 3: https://docs.python.org/3/
.. _setuptools: https://setuptools.readthedocs.io
.. _configparser: https://docs.python.org/3/library/configparser.html
.. _psutil: https://github.com/giampaolo/psutil
.. _lxml: http://lxml.de/
.. _MPD: http://www.musicpd.org/
.. _python-mpd2: https://pypi.python.org/pypi/python-mpd2
.. _Kodi: https://kodi.tv/
.. _requests: https://pypi.python.org/pypi/requests
.. _systemd: https://www.freedesktop.org/wiki/Software/systemd/
.. _systemd service files: http://www.freedesktop.org/software/systemd/man/systemd.service.html
.. _broadcast-logging: https://github.com/languitar/broadcast-logging
.. |project| replace:: {project}
.. |project_bold| replace:: **{project}**
.. |project_program| replace:: :program:`{project}`'''.format(project=project)
# Intersphinx
intersphinx_mapping = {'python': ('https://docs.python.org/3.6', None)}
# HTML options
html_theme = 'sphinx_rtd_theme'
# html_theme_options = {}
html_static_path = ['_static']
html_sidebars = {
'**': [
'relations.html', # needs 'show_related': True theme option to display
'searchbox.html',
]
}
# MANPAGE options
man_pages = [
('man_command',
'autosuspend',
'autosuspend Documentation',
[author],
1),
('man_config',
'autosuspend.conf',
'autosuspend config file Documentation',
[author],
5),
]
autosuspend-1.0.0/doc/source/configuration_file.inc 0000664 0000000 0000000 00000004207 13206577772 0022513 0 ustar 00root root 0000000 0000000 Syntax
~~~~~~
The |project_program| configuration file uses INI syntax and needs to be processable by the Python `configparser`_ module.
A simple configuration file could look like:
.. code-block:: ini
[general]
interval = 30
idle_time = 900
suspend_cmd = /usr/bin/systemctl suspend
[check.Ping]
enabled = false
hosts = 192.168.0.7
[check.RemoteUsers]
class = Users
enabled = true
name = .*
terminal = .*
host = [0-9].*
The configuration file consists of a ``[general]`` section, which specifies general processing options, and multiple options of the format ``[check.*]``.
These sections describe the checks to execute to determine inactivity.
General Configuration
~~~~~~~~~~~~~~~~~~~~~
The ``[general]`` section contains options controlling the overall behavior of the |project_program| daemon. These are:
.. option:: interval
The time to wait after executing all checks in seconds.
.. option:: idle_time
The required amount of time in seconds with no detected activity before the host will be suspended.
.. option:: suspend_cmd
The command to execute in case the host shall be suspended.
This line can contain additional command line arguments to the command to execute.
Check Configuration
~~~~~~~~~~~~~~~~~~~
For each check to execute, a section with the name format ``[check.*]`` needs to be created.
Each check has a name and an executing class which implements the behavior.
The fraction of the section name ``check.`` determines the name, and in case no class option is given inside the section, also the class which implements the check.
In case the `option:`class` option is specified, the name is completely user-defined and the same check can even be instantiated multiple times with differing names.
For each check, these generic options can be specified:
.. option:: class
Name of the class implementing the check.
If this is not specified, the section name must represent a valid check class (see list below).
.. option:: enabled
Needs to be ``true`` for a check to actually execute.
``false`` is assumed if not specified.
Furthermore, each check might have custom options.
autosuspend-1.0.0/doc/source/configuration_file.rst 0000664 0000000 0000000 00000000227 13206577772 0022550 0 ustar 00root root 0000000 0000000 Configuration File
==================
.. include:: configuration_file.inc
For options of individual checks, please refer to :ref:`available-checks`.
autosuspend-1.0.0/doc/source/debugging.rst 0000664 0000000 0000000 00000002322 13206577772 0020633 0 ustar 00root root 0000000 0000000 Debugging
=========
In case you need to track configuration issues to understand why a system suspends or does not, the extensive logging output of |project_program| might be used.
The command line flag :option:`autosuspend -l` allows to specify a Python logging configuration file which specifies what to log.
The provided `systemd`_ service files (see :ref:`systemd-integration`) already use :file:`/etc/autosuspend-logging.conf` as the standard location and a default file is usually installed.
Each iteration logs exactly which condition detected activity or not.
So you should be able to find out what is going on.
In case one of the conditions you monitor prevents suspending the system if an external connection is established (logged-in users, open TCP port), then the logging configuration file can be changed to use the `broadcast-logging`_ package.
This way, the server will broadcast new log messages on the network and external clients on the same network can listen to these messages without creating an explicit connection.
Please refer to the documentation of the `broadcast-logging`_ package on how to enable and use it.
Additionally, one might also examine the ``journalctl`` for |project_program| after the fact.
autosuspend-1.0.0/doc/source/description.inc 0000664 0000000 0000000 00000001056 13206577772 0021167 0 ustar 00root root 0000000 0000000 |project_program| is a daemon that periodically that suspends a system on inactivity.
For this purpose, it periodically iterates a number of user-configurable checks, which shall indicate whether a certain activity on the host is currently present that should prevent the host from suspending.
In case one of the checks indicates such activity, no action is taken and periodic checking continues.
Otherwise, in case no activity can be detected, this state needs to be present for a specified amount of time before the host is suspended by |project_program|.
autosuspend-1.0.0/doc/source/index.rst 0000664 0000000 0000000 00000000601 13206577772 0020005 0 ustar 00root root 0000000 0000000 |project| - a daemon to suspend a system on inactivity
======================================================
.. include:: description.inc
.. toctree::
:maxdepth: 2
:caption: Contents:
installation
configuration_file
available_checks
systemd_integration
debugging
manpages
support
Indices and tables
==================
* :ref:`genindex`
* :ref:`search`
autosuspend-1.0.0/doc/source/installation.rst 0000664 0000000 0000000 00000002260 13206577772 0021402 0 ustar 00root root 0000000 0000000 Installation instructions
=========================
|project_program| is designed for Python **3** and does not work with Python 2.
Requirements
------------
* `Python 3`_
* `psutil`_
Additionally, the some checks need the following dependencies to function properly:
* `python-mpd2`_
* `requests`_
* `lxml`_
Please refer to :ref:`available-checks` for further details on these checks in which check requires which optional dependency.
Binary packages
---------------
There is currently an `Archlinux AUR package `_ for |project|.
In case you want to generate a package for a different Linux distribution, I'd be glad to hear about that.
From-source installation
------------------------
|project_program| provides a usual :file:`setup.py` file for installation using common `setuptools`_ methods.
Briefly, the following steps are necessary to install |project_program|:
.. code-block:: bash
git clone https://github.com/languitar/autosuspend.git
cd autosuspend
python3 setup.py install # with desired options
To build the documentation, the following command can be used:
.. code-block:: bash
python3 setup.py build_sphinx
autosuspend-1.0.0/doc/source/man_command.rst 0000664 0000000 0000000 00000003021 13206577772 0021146 0 ustar 00root root 0000000 0000000 .. _man-command:
|project|
=========
Synopsis
--------
|project_bold| [*options*]
Description
-----------
.. include:: description.inc
If not specified via a command line argument, |project_program| looks for a default configuration at :file:`/etc/autosuspend.conf`.
:manpage:`autosuspend.conf(5)` describes the configuration file, the available checks, and their configuration options.
Options
-------
.. program:: autosuspend
.. option:: -h, --help
Displays an online help.
.. option:: -c FILE, --config FILE
Specifies an alternate config file to use instead of the default on at :file:`/etc/autosuspend.conf`.
.. option:: -a, --allchecks
Usually, |project_program| stops checks in each iteration as soon as the first matching check indicates system activity.
If this flag is set, all subsequent checks are still executed.
Usefull mostly for debugging purposes.
.. option:: -r SECONDS, --runfor SECONDS
If specified, do not run endlessly.
Instead, operate only for the specified amount of seconds, then exit.
Usefull mostly for debugging purposes.
.. option:: -l [FILE], --logging [FILE]
If used without a file argument, enable debug logging (use as last argument).
If used with a file, configure logging with the provided logging file.
This file needs to follow the conventions for :ref:`Python logging files `.
Bugs
----
Please report bugs at the project repository at https://github.com/languitar/autosuspend.
See also
--------
:manpage:`autosuspend.conf(5)`
autosuspend-1.0.0/doc/source/man_config.rst 0000664 0000000 0000000 00000000421 13206577772 0020776 0 ustar 00root root 0000000 0000000 |project|.conf
==============
Synopsis
--------
:file:`/etc/autosuspend.conf`
Description
-----------
Configures the |project_program| daemon.
.. include:: configuration_file.inc
.. include:: available_checks.inc
The options of individual checks are outlined below.
autosuspend-1.0.0/doc/source/manpages.rst 0000664 0000000 0000000 00000000116 13206577772 0020472 0 ustar 00root root 0000000 0000000 Manpages
========
.. toctree::
:maxdepth: 1
man_command
man_config
autosuspend-1.0.0/doc/source/support.rst 0000664 0000000 0000000 00000000222 13206577772 0020411 0 ustar 00root root 0000000 0000000 Support
=======
In case you have found a bug or you want to request a new feature, please open an issue at the `Github project `_.
autosuspend-1.0.0/doc/source/systemd_integration.rst 0000664 0000000 0000000 00000003524 13206577772 0023000 0 ustar 00root root 0000000 0000000 .. _systemd-integration:
systemd integration
===================
Even though it is possible to run |project_program| manually (cf. :ref:`the manpage `), in production use cases, the daemon will usually be run from `systemd`_.
For this purpose, the package ships with `service definition files `_ for `systemd`_, so that you should be able to manage |project_program| via `systemd`_.
These files need to be installed in the appropriate locations for such service files, which depend on the Linux distribution.
Some common locations are:
* :file:`/usr/lib/systemd/system` (e.g. Archlinux packaged service files)
* :file:`/lib/systemd/system` (e.g. Debian packaged service files)
* :file:`/etc/systemd/system` (e.g. Archlinux manually added service files)
Binary installation packages for Linux distributions should have installed the service files at the appropriate locations already.
To start |project_program| via `systemd`_, execute:
.. code-block:: bash
systemctl enable autosuspend.service
To start |project_program| automatically at system start, execute:
.. code-block:: bash
systemctl start autosuspend.service
Preventing the system from sleeping immediately after waking up
---------------------------------------------------------------
Unfortunately, |project_program| does not detect automatically if the system was placed into suspend mode manually.
Therefore, it might happen that after waking up again, all checks have indicated inactivity for a long time (the whole phase of sleeping) and |project_program| might initiate suspending again immediately.
To prevent this, `systemd`_ needs to inform |project_program| every time the system suspends.
This is achieved by a seconds service file, which needs to be enabled (not started):
.. code-block:: bash
systemctl enable autosuspend-detect-suspend.service
autosuspend-1.0.0/pylintrc 0000664 0000000 0000000 00000000106 13206577772 0015666 0 ustar 00root root 0000000 0000000 [MESSAGES]
disable=locally-disabled,locally-enabled,missing-docstring
autosuspend-1.0.0/setup.cfg 0000664 0000000 0000000 00000000125 13206577772 0015721 0 ustar 00root root 0000000 0000000 [aliases]
test=pytest
[build_sphinx]
source-dir = doc/source
build-dir = doc/build
autosuspend-1.0.0/setup.py 0000664 0000000 0000000 00000002132 13206577772 0015612 0 ustar 00root root 0000000 0000000 import os
import os.path
from setuptools import setup
name = 'autosuspend'
with open(os.path.join(
os.path.abspath(os.path.dirname(os.path.realpath(__file__))),
'VERSION'), 'r') as version_file:
lines = version_file.readlines()
release = lines[1].strip()
setup(
name=name,
version=release,
description='A daemon to suspend your server in case of inactivity',
author='Johannes Wienke',
author_email='languitar@semipol.de',
license='GPL2',
zip_safe=False,
setup_requires=[
'pytest-runner',
],
install_requires=[
'psutil>=5.0',
],
extras_require={
'Mpd': ['python-mpd2'],
'Kodi': ['requests'],
'XPath': ['lxml', 'requests'],
},
tests_require=[
'pytest',
'pytest-cov',
'pytest-mock',
],
scripts=[
'autosuspend'
],
data_files=[
('etc', ['autosuspend.conf',
'autosuspend-logging.conf']),
('lib/systemd/system', ['autosuspend.service',
'autosuspend-detect-suspend.service'])
],
)
autosuspend-1.0.0/test_autosuspend.py 0000664 0000000 0000000 00000065653 13206577772 0020104 0 ustar 00root root 0000000 0000000 import configparser
import logging
import os.path
import re
import socket
import subprocess
import unittest.mock
import psutil
import pytest
import requests.exceptions
import autosuspend
class TestCheck(object):
class DummyCheck(autosuspend.Check):
@classmethod
def create(cls, name, config):
pass
def check(self):
pass
def test_name(self):
name = 'test'
assert self.DummyCheck(name).name == name
def test_name_default(self):
assert self.DummyCheck().name is not None
def test_str(self):
assert isinstance(str(self.DummyCheck('test')), str)
class TestSmb(object):
def test_no_connections(self, monkeypatch):
def return_data(*args, **kwargs):
with open(os.path.join(os.path.dirname(__file__), 'test_data',
'smbstatus_no_connections'), 'rb') as f:
return f.read()
monkeypatch.setattr(subprocess, 'check_output', return_data)
assert autosuspend.Smb('foo').check() is None
def test_with_connections(self, monkeypatch):
def return_data(*args, **kwargs):
with open(os.path.join(os.path.dirname(__file__), 'test_data',
'smbstatus_with_connections'), 'rb') as f:
return f.read()
monkeypatch.setattr(subprocess, 'check_output', return_data)
assert autosuspend.Smb('foo').check() is not None
assert len(autosuspend.Smb('foo').check().splitlines()) == 3
def test_call_error(self, mocker):
mocker.patch('subprocess.check_output',
side_effect=subprocess.CalledProcessError(2, 'cmd'))
with pytest.raises(autosuspend.SevereCheckError):
autosuspend.Smb('foo').check()
def test_create(self):
assert isinstance(autosuspend.Smb.create('name', None),
autosuspend.Smb)
class TestUsers(object):
@staticmethod
def create_suser(name, terminal, host, started, pid):
try:
return psutil._common.suser(name, terminal, host, started, pid)
except TypeError:
# psutil 5.0
return psutil._common.suser(name, terminal, host, started)
def test_no_users(self, monkeypatch):
def data():
return []
monkeypatch.setattr(psutil, 'users', data)
assert autosuspend.Users('users', re.compile('.*'), re.compile('.*'),
re.compile('.*')).check() is None
def test_smoke(self):
autosuspend.Users('users', re.compile('.*'), re.compile('.*'),
re.compile('.*')).check()
def test_matching_users(self, monkeypatch):
def data():
return [self.create_suser('foo', 'pts1', 'host', 12345, 12345)]
monkeypatch.setattr(psutil, 'users', data)
assert autosuspend.Users('users', re.compile('.*'), re.compile('.*'),
re.compile('.*')).check() is not None
def test_non_matching_user(self, monkeypatch):
def data():
return [self.create_suser('foo', 'pts1', 'host', 12345, 12345)]
monkeypatch.setattr(psutil, 'users', data)
assert autosuspend.Users('users', re.compile('narf'), re.compile('.*'),
re.compile('.*')).check() is None
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
name = name.*name
terminal = term.*term
host = host.*host''')
check = autosuspend.Users.create('name', parser['section'])
assert check._user_regex == re.compile('name.*name')
assert check._terminal_regex == re.compile('term.*term')
assert check._host_regex == re.compile('host.*host')
def test_create_regex_error(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
name = name.*name
terminal = term.[[a-9]term
host = host.*host''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.Users.create('name', parser['section'])
class TestProcesses(object):
class StubProcess(object):
def __init__(self, name):
self._name = name
def name(self):
return self._name
class RaisingProcess(object):
def name(self):
raise psutil.NoSuchProcess(42)
def test_matching_process(self, monkeypatch):
def data():
return [self.StubProcess('blubb'), self.StubProcess('nonmatching')]
monkeypatch.setattr(psutil, 'process_iter', data)
assert autosuspend.Processes(
'foo', ['dummy', 'blubb', 'other']).check() is not None
def test_ignore_no_such_process(self, monkeypatch):
def data():
return [self.RaisingProcess()]
monkeypatch.setattr(psutil, 'process_iter', data)
autosuspend.Processes('foo', ['dummy']).check()
def test_non_matching_process(self, monkeypatch):
def data():
return [self.StubProcess('asdfasdf'),
self.StubProcess('nonmatching')]
monkeypatch.setattr(psutil, 'process_iter', data)
assert autosuspend.Processes(
'foo', ['dummy', 'blubb', 'other']).check() is None
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
processes = foo, bar, narf''')
assert autosuspend.Processes.create(
'name', parser['section'])._processes == ['foo', 'bar', 'narf']
def test_create_no_entry(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.Processes.create('name', parser['section'])
class TestActiveConnection(object):
MY_PORT = 22
MY_ADDRESS = '123.456.123.456'
def test_smoke(self):
autosuspend.ActiveConnection('foo', [22]).check()
def test_connected(self, monkeypatch):
def addresses():
return {'dummy': [psutil._common.snic(
socket.AF_INET, self.MY_ADDRESS, '255.255.255.0',
None, None)]}
def connections():
return [psutil._common.sconn(
-1, socket.AF_INET, socket.SOCK_STREAM,
(self.MY_ADDRESS, self.MY_PORT),
('42.42.42.42', 42), 'ESTABLISHED', None)]
monkeypatch.setattr(psutil, 'net_if_addrs', addresses)
monkeypatch.setattr(psutil, 'net_connections', connections)
assert autosuspend.ActiveConnection(
'foo', [10, self.MY_PORT, 30]).check() is not None
@pytest.mark.parametrize("connection", [
# not my port
psutil._common.sconn(-1,
socket.AF_INET, socket.SOCK_STREAM,
(MY_ADDRESS, 32),
('42.42.42.42', 42),
'ESTABLISHED', None),
# not my local address
psutil._common.sconn(-1,
socket.AF_INET, socket.SOCK_STREAM,
('33.33.33.33', MY_PORT),
('42.42.42.42', 42),
'ESTABLISHED', None),
# not my established
psutil._common.sconn(-1,
socket.AF_INET, socket.SOCK_STREAM,
(MY_ADDRESS, MY_PORT),
('42.42.42.42', 42),
'NARF', None),
# I am the client
psutil._common.sconn(-1,
socket.AF_INET, socket.SOCK_STREAM,
('42.42.42.42', 42),
(MY_ADDRESS, MY_PORT),
'NARF', None),
])
def test_not_connected(self, monkeypatch, connection):
def addresses():
return {'dummy': [psutil._common.snic(
socket.AF_INET, self.MY_ADDRESS, '255.255.255.0',
None, None)]}
def connections():
return [connection]
monkeypatch.setattr(psutil, 'net_if_addrs', addresses)
monkeypatch.setattr(psutil, 'net_connections', connections)
assert autosuspend.ActiveConnection(
'foo', [10, self.MY_PORT, 30]).check() is None
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
ports = 10,20,30''')
assert autosuspend.ActiveConnection.create(
'name', parser['section'])._ports == set([10, 20, 30])
def test_create_no_entry(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.ActiveConnection.create('name', parser['section'])
def test_create_no_number(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
ports = 10,20xx,30''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.ActiveConnection.create('name', parser['section'])
class TestLoad(object):
def test_below(self, monkeypatch):
threshold = 1.34
def data():
return [0, threshold - 0.2, 0]
monkeypatch.setattr(os, 'getloadavg', data)
assert autosuspend.Load('foo', threshold).check() is None
def test_above(self, monkeypatch):
threshold = 1.34
def data():
return [0, threshold + 0.2, 0]
monkeypatch.setattr(os, 'getloadavg', data)
assert autosuspend.Load('foo', threshold).check() is not None
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
threshold = 3.2''')
assert autosuspend.Load.create(
'name', parser['section'])._threshold == 3.2
def test_create_no_number(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
threshold = narf''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.Load.create('name', parser['section'])
class TestMpd(object):
def test_playing(self, monkeypatch):
check = autosuspend.Mpd('test', None, None, None)
def get_state():
return {'state': 'play'}
monkeypatch.setattr(check, '_get_state', get_state)
assert check.check() is not None
def test_not_playing(self, monkeypatch):
check = autosuspend.Mpd('test', None, None, None)
def get_state():
return {'state': 'pause'}
monkeypatch.setattr(check, '_get_state', get_state)
assert check.check() is None
def test_correct_mpd_interaction(self, mocker):
import mpd
mock_instance = mocker.MagicMock(spec=mpd.MPDClient)
mock_instance.status.return_value = {'state': 'play'}
timeout_property = mocker.PropertyMock()
type(mock_instance).timeout = timeout_property
mock = mocker.patch('mpd.MPDClient')
mock.return_value = mock_instance
host = 'foo'
port = 42
timeout = 17
assert autosuspend.Mpd('name', host, port, timeout).check() is not None
timeout_property.assert_called_once_with(timeout)
mock_instance.connect.assert_called_once_with(host, port)
mock_instance.status.assert_called_once_with()
mock_instance.close.assert_called_once_with()
mock_instance.disconnect.assert_called_once_with()
def test_handle_connection_errors(self):
check = autosuspend.Mpd('test', None, None, None)
def _get_state():
raise ConnectionError()
check._get_state = _get_state
with pytest.raises(autosuspend.TemporaryCheckError):
check.check()
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
host = host
port = 1234
timeout = 12''')
check = autosuspend.Mpd.create('name', parser['section'])
assert check._host == 'host'
assert check._port == 1234
assert check._timeout == 12
def test_create_port_no_number(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
host = host
port = string
timeout = 12''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.Mpd.create('name', parser['section'])
def test_create_timeout_no_number(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
host = host
port = 10
timeout = string''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.Mpd.create('name', parser['section'])
class TestKodi(object):
def test_playing(self, mocker):
mock_reply = mocker.MagicMock()
mock_reply.json.return_value = {
"id": 1, "jsonrpc": "2.0",
"result": [{"playerid": 0, "type": "audio"}]}
mocker.patch('requests.get', return_value=mock_reply)
assert autosuspend.Kodi('foo', 'url', 10).check() is not None
mock_reply.json.assert_called_once_with()
def test_not_playing(self, mocker):
mock_reply = mocker.MagicMock()
mock_reply.json.return_value = {
"id": 1, "jsonrpc": "2.0", "result": []}
mocker.patch('requests.get', return_value=mock_reply)
assert autosuspend.Kodi('foo', 'url', 10).check() is None
mock_reply.json.assert_called_once_with()
def test_assertion_no_result(self, mocker):
mock_reply = mocker.MagicMock()
mock_reply.json.return_value = {"id": 1, "jsonrpc": "2.0"}
mocker.patch('requests.get', return_value=mock_reply)
with pytest.raises(autosuspend.TemporaryCheckError):
autosuspend.Kodi('foo', 'url', 10).check()
def test_request_error(self, mocker):
mocker.patch('requests.get',
side_effect=requests.exceptions.RequestException())
with pytest.raises(autosuspend.TemporaryCheckError):
autosuspend.Kodi('foo', 'url', 10).check()
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
url = anurl
timeout = 12''')
check = autosuspend.Kodi.create('name', parser['section'])
assert check._url == 'anurl'
assert check._timeout == 12
def test_create_timeout_no_number(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
url = anurl
timeout = string''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.Kodi.create('name', parser['section'])
class TestPing(object):
def test_smoke(self, mocker):
mock = mocker.patch('subprocess.call')
mock.return_value = 1
hosts = ['abc', '129.123.145.42']
assert autosuspend.Ping('name', hosts).check() is None
assert mock.call_count == len(hosts)
for (args, _), host in zip(mock.call_args_list, hosts):
assert args[0][-1] == host
def test_matching(self, mocker):
mock = mocker.patch('subprocess.call')
mock.return_value = 0
assert autosuspend.Ping('name', ['foo']).check() is not None
def test_create_missing_hosts(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.Ping.create('name', parser['section'])
def test_create_host_splitting(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
hosts=a,b,c''')
ping = autosuspend.Ping.create('name', parser['section'])
assert ping._hosts == ['a', 'b', 'c']
class TestXIdleTime(object):
def test_create_default(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]''')
check = autosuspend.XIdleTime.create('name', parser['section'])
assert check._timeout == 600
assert check._ignore_process_re == re.compile(r'a^')
assert check._ignore_users_re == re.compile(r'^a')
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
timeout = 42
ignore_if_process = .*test
ignore_users = test.*test''')
check = autosuspend.XIdleTime.create('name', parser['section'])
assert check._timeout == 42
assert check._ignore_process_re == re.compile(r'.*test')
assert check._ignore_users_re == re.compile(r'test.*test')
def test_create_no_int(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
timeout = string''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.XIdleTime.create('name', parser['section'])
def test_create_broken_process_re(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
ignore_if_process = [[a-9]''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.XIdleTime.create('name', parser['section'])
def test_create_broken_users_re(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
ignore_users = [[a-9]''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.XIdleTime.create('name', parser['section'])
class TestExternalCommand(object):
def test_create(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]
command = narf bla ''')
check = autosuspend.ExternalCommand.create('name', parser['section'])
assert check._command == 'narf bla'
def test_create_no_command(self):
parser = configparser.ConfigParser()
parser.read_string('''[section]''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.ExternalCommand.create('name', parser['section'])
def test_check(self, mocker):
mock = mocker.patch('subprocess.check_call')
parser = configparser.ConfigParser()
parser.read_string('''[section]
command = foo bar''')
assert autosuspend.ExternalCommand.create(
'name', parser['section']).check() is not None
mock.assert_called_once_with('foo bar', shell=True)
def test_check_no_match(self, mocker):
mock = mocker.patch('subprocess.check_call')
mock.side_effect = subprocess.CalledProcessError(2, 'foo bar')
parser = configparser.ConfigParser()
parser.read_string('''[section]
command = foo bar''')
assert autosuspend.ExternalCommand.create(
'name', parser['section']).check() is None
mock.assert_called_once_with('foo bar', shell=True)
class TestXPath(object):
def test_matching(self, mocker):
mock_reply = mocker.MagicMock()
text_property = mocker.PropertyMock()
type(mock_reply).text = text_property
text_property.return_value = ""
mock_method = mocker.patch('requests.get', return_value=mock_reply)
url = 'nourl'
assert autosuspend.XPath('foo', '/a', url).check() is not None
mock_method.assert_called_once_with(url)
text_property.assert_called_once_with()
def test_not_matching(self, mocker):
mock_reply = mocker.MagicMock()
text_property = mocker.PropertyMock()
type(mock_reply).text = text_property
text_property.return_value = ""
mocker.patch('requests.get', return_value=mock_reply)
assert autosuspend.XPath('foo', '/b', 'nourl').check() is None
def test_broken_xml(self, mocker):
with pytest.raises(autosuspend.TemporaryCheckError):
mock_reply = mocker.MagicMock()
text_property = mocker.PropertyMock()
type(mock_reply).text = text_property
text_property.return_value = "//broken"
mocker.patch('requests.get', return_value=mock_reply)
autosuspend.XPath('foo', '/b', 'nourl').check()
def test_xpath_prevalidation(self):
with pytest.raises(autosuspend.ConfigurationError,
match=r'^Invalid xpath.*'):
parser = configparser.ConfigParser()
parser.read_string('''[section]
xpath=|34/ad
url=nourl''')
autosuspend.XPath.create('name', parser['section'])
@pytest.mark.parametrize('entry,', ['xpath', 'url'])
def test_missing_config_entry(self, entry):
with pytest.raises(autosuspend.ConfigurationError,
match=r"^No '" + entry + "'.*"):
parser = configparser.ConfigParser()
parser.read_string('''[section]
xpath=/valid
url=nourl''')
del parser['section'][entry]
autosuspend.XPath.create('name', parser['section'])
def test_execute_suspend(mocker):
mock = mocker.patch('subprocess.check_call')
command = ['foo', 'bar']
autosuspend.execute_suspend(command)
mock.assert_called_once_with(command, shell=True)
def test_execute_suspend_call_exception(mocker):
mock = mocker.patch('subprocess.check_call')
command = ['foo', 'bar']
mock.side_effect = subprocess.CalledProcessError(2, command)
spy = mocker.spy(autosuspend._logger, 'warning')
autosuspend.execute_suspend(command)
mock.assert_called_once_with(command, shell=True)
assert spy.call_count == 1
def test_configure_logging_debug(mocker):
mock = mocker.patch('logging.basicConfig')
autosuspend.configure_logging(True)
mock.assert_called_once_with(level=logging.DEBUG)
def test_configure_logging_standard(mocker):
mock = mocker.patch('logging.basicConfig')
autosuspend.configure_logging(False)
mock.assert_called_once_with(level=logging.WARNING)
def test_configure_logging_file(mocker):
mock = mocker.patch('logging.config.fileConfig')
# anything that is not a boolean is treated like a file
autosuspend.configure_logging(42)
mock.assert_called_once_with(42)
def test_configure_logging_file_fallback(mocker):
mock = mocker.patch('logging.config.fileConfig',
side_effect=RuntimeError())
mock_basic = mocker.patch('logging.basicConfig')
# anything that is not a boolean is treated like a file
autosuspend.configure_logging(42)
mock.assert_called_once_with(42)
mock_basic.assert_called_once_with(level=logging.WARNING)
def test_set_up_checks(mocker):
mock_class = mocker.patch('autosuspend.Mpd')
mock_class.create.return_value = mocker.MagicMock(spec=autosuspend.Check)
parser = configparser.ConfigParser()
parser.read_string('''[check.Foo]
class = Mpd
enabled = True''')
autosuspend.set_up_checks(parser)
mock_class.create.assert_called_once_with('Foo', parser['check.Foo'])
def test_set_up_checks_not_enabled(mocker):
mock_class = mocker.patch('autosuspend.Mpd')
mock_class.create.return_value = mocker.MagicMock(spec=autosuspend.Check)
parser = configparser.ConfigParser()
parser.read_string('''[check.Foo]
class = Mpd
enabled = False''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.set_up_checks(parser)
def test_set_up_checks_no_such_class(mocker):
parser = configparser.ConfigParser()
parser.read_string('''[check.Foo]
class = FooBarr
enabled = True''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.set_up_checks(parser)
def test_set_up_checks_not_a_check(mocker):
mock_class = mocker.patch('autosuspend.Mpd')
mock_class.create.return_value = mocker.MagicMock()
parser = configparser.ConfigParser()
parser.read_string('''[check.Foo]
class = Mpd
enabled = True''')
with pytest.raises(autosuspend.ConfigurationError):
autosuspend.set_up_checks(parser)
mock_class.create.assert_called_once_with('Foo', parser['check.Foo'])
class TestExecuteChecks(object):
def test_no_checks(self, mocker):
assert autosuspend.execute_checks(
[], False, mocker.MagicMock()) is False
def test_matches(self, mocker):
matching_check = mocker.MagicMock(spec=autosuspend.Check)
matching_check.name = 'foo'
matching_check.check.return_value = "matches"
assert autosuspend.execute_checks(
[matching_check], False, mocker.MagicMock()) is True
matching_check.check.assert_called_once_with()
def test_only_first_called(self, mocker):
matching_check = mocker.MagicMock(spec=autosuspend.Check)
matching_check.name = 'foo'
matching_check.check.return_value = "matches"
second_check = mocker.MagicMock()
second_check.name = 'bar'
second_check.check.return_value = "matches"
assert autosuspend.execute_checks(
[matching_check, second_check],
False,
mocker.MagicMock()) is True
matching_check.check.assert_called_once_with()
second_check.check.assert_not_called()
def test_all_called(self, mocker):
matching_check = mocker.MagicMock(spec=autosuspend.Check)
matching_check.name = 'foo'
matching_check.check.return_value = "matches"
second_check = mocker.MagicMock()
second_check.name = 'bar'
second_check.check.return_value = "matches"
assert autosuspend.execute_checks(
[matching_check, second_check],
True,
mocker.MagicMock()) is True
matching_check.check.assert_called_once_with()
second_check.check.assert_called_once_with()
def test_ignore_temporary_errors(self, mocker):
matching_check = mocker.MagicMock(spec=autosuspend.Check)
matching_check.name = 'foo'
matching_check.check.side_effect = autosuspend.TemporaryCheckError()
second_check = mocker.MagicMock()
second_check.name = 'bar'
second_check.check.return_value = "matches"
assert autosuspend.execute_checks(
[matching_check, second_check],
False,
mocker.MagicMock()) is True
matching_check.check.assert_called_once_with()
second_check.check.assert_called_once_with()
autosuspend-1.0.0/test_data/ 0000775 0000000 0000000 00000000000 13206577772 0016052 5 ustar 00root root 0000000 0000000 autosuspend-1.0.0/test_data/dont_suspend.conf 0000664 0000000 0000000 00000000176 13206577772 0021432 0 ustar 00root root 0000000 0000000 [general]
interval = 2
idle_time = 5
suspend_cmd = touch would_suspend
[check.ExternalCommand]
enabled = True
command = true
autosuspend-1.0.0/test_data/smbstatus_no_connections 0000664 0000000 0000000 00000000447 13206577772 0023125 0 ustar 00root root 0000000 0000000
Samba version 4.7.0
PID Username Group Machine Protocol Version Encryption Signing
----------------------------------------------------------------------------------------------------------------------------------------
autosuspend-1.0.0/test_data/smbstatus_with_connections 0000664 0000000 0000000 00000000421 13206577772 0023454 0 ustar 00root root 0000000 0000000
Samba version 3.5.1
PID Username Group Machine
-------------------------------------------------------------------
14944 it 131.169.214.117 (131.169.214.117)
14944 it 131.169.214.117 (131.169.214.117)
autosuspend-1.0.0/test_data/would_suspend.conf 0000664 0000000 0000000 00000000177 13206577772 0021621 0 ustar 00root root 0000000 0000000 [general]
interval = 2
idle_time = 5
suspend_cmd = touch would_suspend
[check.ExternalCommand]
enabled = True
command = false
autosuspend-1.0.0/test_integration.py 0000664 0000000 0000000 00000001711 13206577772 0020036 0 ustar 00root root 0000000 0000000 import os
import os.path
import pytest
import autosuspend
ROOT = os.path.dirname(os.path.realpath(__file__))
SUSPENSION_FILE = 'would_suspend'
@pytest.fixture
def suspension_file():
try:
os.remove(SUSPENSION_FILE)
except OSError as error:
pass
class SuspensionFileFixture(object):
def exists(self):
return os.path.exists(SUSPENSION_FILE)
yield SuspensionFileFixture()
try:
os.remove(SUSPENSION_FILE)
except OSError as error:
pass
def test_no_suspend_if_matching(suspension_file):
autosuspend.main([
'-c',
os.path.join(ROOT, 'test_data', 'dont_suspend.conf'),
'-r',
'10',
'-l'])
assert not suspension_file.exists()
def test_suspend(suspension_file):
autosuspend.main([
'-c',
os.path.join(ROOT, 'test_data', 'would_suspend.conf'),
'-r',
'10',
'-l'])
assert suspension_file.exists()