IMMREX7
# -*- coding: utf-8 -*-
import logging
from subprocess import PIPE, call, CalledProcessError
from typing import Any, Dict # pylint: disable=W0611 # noqa: F401
LOGGER = logging.getLogger(__name__)
class BaseDaemon:
"""A base implementation of a daemon"""
def __init__(self, name: str, command_fmt: str) -> None:
self.name = name
self.command_fmt = command_fmt
def _run(self, action: str, check_return_code: bool = True, pipes: bool = True) -> Any:
"""Run an action for the daemon.
:param action: The action to be run
:param check_return_code: Whether to error on non-zero return codes
:param pipes:
:raises CalledProcessError: If `check_return_code` is True, and a non-zero return code occurs
"""
LOGGER.info('%sing %s', action, self.name)
kwargs = {'universal_newlines': True, 'timeout': 10} # type: Dict[str, Any]
if pipes:
kwargs.update({'stdout': PIPE, 'stderr': PIPE})
cmd = self.command_fmt.format(name=self.name, action=action)
result = call(cmd.split(), **kwargs)
LOGGER.info(result)
if check_return_code:
if result != 0:
raise CalledProcessError(returncode=result, cmd=cmd)
return result
def status(self) -> Any:
"""Check the status of the daemon."""
return self._run('status', check_return_code=False)
def start(self) -> Any:
"""Start the daemon."""
# Must not connect pipes to stdin/out, or subprocess will never
# complete, hanging on communicate() call.
return self._run('start', pipes=False)
def stop(self) -> Any:
"""Stop the daemon."""
return self._run('stop')
def restart(self) -> Any:
"""Restart the daemon."""
# Must not connect pipes to stdin/out, or subprocess will never
# complete, hanging on communicate() call.
return self._run('restart', pipes=False)
Copyright © 2021 -