service: Add privileged utility for 'try-reload-or-restart' action

Reload a service if it supports reloading, otherwise restart. Do nothing if
service is not running.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
This commit is contained in:
Sunil Mohan Adapa 2024-09-16 12:01:16 -07:00 committed by Veiko Aasa
parent ec25b3a046
commit 92a61f422c
No known key found for this signature in database
GPG Key ID: 478539CAE680674E
4 changed files with 25 additions and 3 deletions

View File

@ -135,6 +135,14 @@ def service_reload(service_name):
service_action(service_name, 'reload')
def service_try_reload_or_restart(service_name):
"""Reload a service if it supports reloading, otherwise restart.
Do nothing if service is not running.
"""
service_action(service_name, 'try-reload-or-restart')
def service_action(service_name, action):
"""Perform the given action on the service_name."""
subprocess.run(['systemctl', action, service_name],

View File

@ -5,11 +5,12 @@ from .config import dropin_is_valid, dropin_link, dropin_unlink
from .packages import (filter_conffile_packages, install,
is_package_manager_busy, remove, update)
from .service import (disable, enable, is_enabled, is_running, mask, reload,
restart, start, stop, try_restart, unmask)
restart, start, stop, try_reload_or_restart, try_restart,
unmask)
__all__ = [
'filter_conffile_packages', 'install', 'is_package_manager_busy', 'remove',
'update', 'disable', 'enable', 'is_enabled', 'is_running', 'mask',
'reload', 'restart', 'start', 'stop', 'try_restart', 'unmask',
'dropin_is_valid', 'dropin_link', 'dropin_unlink'
'reload', 'restart', 'start', 'stop', 'try_reload_or_restart',
'try_restart', 'unmask', 'dropin_is_valid', 'dropin_link', 'dropin_unlink'
]

View File

@ -57,6 +57,16 @@ def reload(service: str):
action_utils.service_reload(service)
@privileged
def try_reload_or_restart(service: str):
"""Reload a service if it supports reloading, otherwise restart.
Do nothing if service is not running.
"""
_assert_service_is_managed_by_plinth(service)
action_utils.service_try_reload_or_restart(service)
@privileged
def mask(service: str):
"""Mask a service."""

View File

@ -16,6 +16,7 @@ from plinth.action_utils import (get_addresses, get_hostname,
service_is_enabled, service_is_running,
service_reload, service_restart,
service_start, service_stop,
service_try_reload_or_restart,
service_try_restart, service_unmask)
UNKNOWN = 'unknowndeamon'
@ -86,6 +87,8 @@ def test_service_actions(mock):
mock.assert_called_with(UNKNOWN, 'try-restart')
service_reload(UNKNOWN)
mock.assert_called_with(UNKNOWN, 'reload')
service_try_reload_or_restart(UNKNOWN)
mock.assert_called_with(UNKNOWN, 'try-reload-or-restart')
@pytest.mark.usefixtures('needs_root')