charmlibs-systemd 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,65 @@
1
+ # Copyright 2025 Canonical Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Abstractions for stopping, starting and managing system services via systemd.
16
+
17
+ For the most part, we transparently provide an interface to a commonly used selection of
18
+ systemd commands, with a few shortcuts baked in. For example, :func:`service_pause` and
19
+ :func:`service_resume` will run the mask/unmask and enable/disable invocations.
20
+
21
+ Example usage
22
+ -------------
23
+
24
+ .. code-block:: python
25
+
26
+ from charmlibs import systemd
27
+
28
+ # Start a service
29
+ if not systemd.service_running("mysql"):
30
+ success = systemd.service_start("mysql")
31
+
32
+ # Attempt to reload a service, restarting if necessary
33
+ success = systemd.service_reload("nginx", restart_on_failure=True)
34
+ """
35
+
36
+ from ._systemd import (
37
+ SystemdError,
38
+ daemon_reload,
39
+ service_disable,
40
+ service_enable,
41
+ service_failed,
42
+ service_pause,
43
+ service_reload,
44
+ service_restart,
45
+ service_resume,
46
+ service_running,
47
+ service_start,
48
+ service_stop,
49
+ )
50
+ from ._version import __version__ as __version__
51
+
52
+ __all__ = [
53
+ 'SystemdError',
54
+ 'daemon_reload',
55
+ 'service_disable',
56
+ 'service_enable',
57
+ 'service_failed',
58
+ 'service_pause',
59
+ 'service_reload',
60
+ 'service_restart',
61
+ 'service_resume',
62
+ 'service_running',
63
+ 'service_start',
64
+ 'service_stop',
65
+ ]
@@ -0,0 +1,241 @@
1
+ # Copyright 2025 Canonical Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Manage services controlled by systemd."""
16
+
17
+ import logging
18
+ import subprocess
19
+
20
+ _logger = logging.getLogger(__name__)
21
+
22
+
23
+ class SystemdError(Exception):
24
+ """Custom exception for systemd related errors."""
25
+
26
+
27
+ def _systemctl(*args: str, check: bool = False) -> int:
28
+ """Call a `systemctl` command with logging enabled.
29
+
30
+ Args:
31
+ args: Arguments to pass to the `systemctl` command.
32
+ check: If set to `True`, raise an error if the command exits with a non-zero exit code.
33
+
34
+ Returns:
35
+ Returncode of `systemctl` command execution.
36
+
37
+ Raises:
38
+ SystemdError:
39
+ Raised if the called command fails and check is set to `True`.
40
+ """
41
+ cmd = ['systemctl', *args]
42
+ _logger.debug('running command %s', cmd)
43
+ try:
44
+ result = subprocess.run(cmd, capture_output=True, text=True, check=check)
45
+ except subprocess.CalledProcessError as e:
46
+ raise SystemdError(
47
+ f'Command {cmd} failed with returncode {e.returncode}. systemctl output:\n'
48
+ + f'stdout: {e.stdout}\n'
49
+ + f'stderr: {e.stderr}'
50
+ ) from None
51
+
52
+ _logger.debug(
53
+ "command '%s' completed with:\nexit code: %s\nstdout: %s\nstderr: %s",
54
+ ' '.join(cmd),
55
+ result.returncode,
56
+ result.stdout,
57
+ result.stderr,
58
+ )
59
+ return result.returncode
60
+
61
+
62
+ def service_running(service_name: str) -> bool:
63
+ """Report whether a system service is running.
64
+
65
+ Args:
66
+ service_name: The name of the service to check.
67
+
68
+ Returns:
69
+ True if service is running/active; False if not.
70
+ """
71
+ # If returncode is 0, this means that is service is active.
72
+ return _systemctl('--quiet', 'is-active', service_name) == 0
73
+
74
+
75
+ def service_failed(service_name: str) -> bool:
76
+ """Report whether a system service has failed.
77
+
78
+ Args:
79
+ service_name: The name of the service to check.
80
+
81
+ Returns:
82
+ True if service is marked as failed; False if not.
83
+ """
84
+ # If returncode is 0, this means that the service has failed.
85
+ return _systemctl('--quiet', 'is-failed', service_name) == 0
86
+
87
+
88
+ def service_start(*args: str) -> bool:
89
+ """Start a system service.
90
+
91
+ Args:
92
+ *args: Arguments to pass to `systemctl start` (normally the service name).
93
+
94
+ Returns:
95
+ On success, this function returns True for historical reasons.
96
+
97
+ Raises:
98
+ SystemdError: Raised if `systemctl start ...` returns a non-zero returncode.
99
+ """
100
+ return _systemctl('start', *args, check=True) == 0
101
+
102
+
103
+ def service_stop(*args: str) -> bool:
104
+ """Stop a system service.
105
+
106
+ Args:
107
+ *args: Arguments to pass to `systemctl stop` (normally the service name).
108
+
109
+ Returns:
110
+ On success, this function returns True for historical reasons.
111
+
112
+ Raises:
113
+ SystemdError: Raised if `systemctl stop ...` returns a non-zero returncode.
114
+ """
115
+ return _systemctl('stop', *args, check=True) == 0
116
+
117
+
118
+ def service_restart(*args: str) -> bool:
119
+ """Restart a system service.
120
+
121
+ Args:
122
+ *args: Arguments to pass to `systemctl restart` (normally the service name).
123
+
124
+ Returns:
125
+ On success, this function returns True for historical reasons.
126
+
127
+ Raises:
128
+ SystemdError: Raised if `systemctl restart ...` returns a non-zero returncode.
129
+ """
130
+ return _systemctl('restart', *args, check=True) == 0
131
+
132
+
133
+ def service_enable(*args: str) -> bool:
134
+ """Enable a system service.
135
+
136
+ Args:
137
+ *args: Arguments to pass to `systemctl enable` (normally the service name).
138
+
139
+ Returns:
140
+ On success, this function returns True for historical reasons.
141
+
142
+ Raises:
143
+ SystemdError: Raised if `systemctl enable ...` returns a non-zero returncode.
144
+ """
145
+ return _systemctl('enable', *args, check=True) == 0
146
+
147
+
148
+ def service_disable(*args: str) -> bool:
149
+ """Disable a system service.
150
+
151
+ Args:
152
+ *args: Arguments to pass to `systemctl disable` (normally the service name).
153
+
154
+ Returns:
155
+ On success, this function returns True for historical reasons.
156
+
157
+ Raises:
158
+ SystemdError: Raised if `systemctl disable ...` returns a non-zero returncode.
159
+ """
160
+ return _systemctl('disable', *args, check=True) == 0
161
+
162
+
163
+ def service_reload(service_name: str, restart_on_failure: bool = False) -> bool:
164
+ """Reload a system service, optionally falling back to restart if reload fails.
165
+
166
+ Args:
167
+ service_name: The name of the service to reload.
168
+ restart_on_failure:
169
+ Boolean indicating whether to fall back to a restart if the reload fails.
170
+
171
+ Returns:
172
+ On success, this function returns True for historical reasons.
173
+
174
+ Raises:
175
+ SystemdError: Raised if `systemctl reload|restart ...` returns a non-zero returncode.
176
+ """
177
+ try:
178
+ return _systemctl('reload', service_name, check=True) == 0
179
+ except SystemdError:
180
+ if restart_on_failure:
181
+ return service_restart(service_name)
182
+ else:
183
+ raise
184
+
185
+
186
+ def service_pause(service_name: str) -> bool:
187
+ """Pause a system service.
188
+
189
+ Stops the service and prevents the service from starting again at boot.
190
+
191
+ Args:
192
+ service_name: The name of the service to pause.
193
+
194
+ Returns:
195
+ On success, this function returns True for historical reasons.
196
+
197
+ Raises:
198
+ SystemdError: Raised if service is still running after being paused by systemctl.
199
+ """
200
+ _systemctl('disable', '--now', service_name)
201
+ _systemctl('mask', service_name)
202
+
203
+ if service_running(service_name):
204
+ raise SystemdError(f'Attempted to pause {service_name!r}, but it is still running.')
205
+
206
+ return True
207
+
208
+
209
+ def service_resume(service_name: str) -> bool:
210
+ """Resume a system service.
211
+
212
+ Re-enable starting the service again at boot. Start the service.
213
+
214
+ Args:
215
+ service_name: The name of the service to resume.
216
+
217
+ Returns:
218
+ On success, this function returns True for historical reasons.
219
+
220
+ Raises:
221
+ SystemdError: Raised if service is not running after being resumed by systemctl.
222
+ """
223
+ _systemctl('unmask', service_name)
224
+ _systemctl('enable', '--now', service_name)
225
+
226
+ if not service_running(service_name):
227
+ raise SystemdError(f'Attempted to resume {service_name!r}, but it is not running.')
228
+
229
+ return True
230
+
231
+
232
+ def daemon_reload() -> bool:
233
+ """Reload systemd manager configuration.
234
+
235
+ Returns:
236
+ On success, this function returns True for historical reasons.
237
+
238
+ Raises:
239
+ SystemdError: Raised if `systemctl daemon-reload` returns a non-zero returncode.
240
+ """
241
+ return _systemctl('daemon-reload', check=True) == 0
@@ -0,0 +1,15 @@
1
+ # Copyright 2025 Canonical Ltd.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ __version__ = '1.0.0'
File without changes
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: charmlibs-systemd
3
+ Version: 1.0.0
4
+ Summary: The charmlibs.systemd package.
5
+ Project-URL: Repository, https://github.com/canonical/charmlibs
6
+ Project-URL: Issues, https://github.com/canonical/charmlibs/issues
7
+ Project-URL: Documentation, https://documentation.ubuntu.com/charmlibs/reference/charmlibs/systemd/
8
+ Project-URL: Changelog, https://github.com/canonical/charmlibs/blob/main/systemd/CHANGELOG.md
9
+ Author: The Charm Tech team at Canonical
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: POSIX :: Linux
14
+ Classifier: Programming Language :: Python :: 3
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+
18
+ # charmlibs.systemd
19
+
20
+ The `systemd` library.
21
+
22
+ To install, add `charmlibs-systemd` to your Python dependencies. Then in your Python code, import as:
23
+
24
+ ```py
25
+ from charmlibs import systemd
26
+ ```
27
+
28
+ See the [reference documentation](https://documentation.ubuntu.com/charmlibs/reference/charmlibs/systemd) for more.
@@ -0,0 +1,7 @@
1
+ charmlibs/systemd/__init__.py,sha256=LXElGX2wHg-fPeQDCWmgkZEFm7hZcLmpI5ntb1kI_UU,1841
2
+ charmlibs/systemd/_systemd.py,sha256=2a56LTyaghQ8a8wxAu3Ec0OK-K0HLQkeKjjhhqFWMTw,7132
3
+ charmlibs/systemd/_version.py,sha256=SOabh2HM3GM1fjRvHHGC-IV789Y2DPLYqgl_cRoScto,597
4
+ charmlibs/systemd/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ charmlibs_systemd-1.0.0.dist-info/METADATA,sha256=I7OBxBRyChJJgmuPZrmYq1qHoNUTGsUjMUeJtnk5RJ0,1095
6
+ charmlibs_systemd-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ charmlibs_systemd-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any