django-systemd 0.1.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,26 @@
1
+ r"""
2
+ ::
3
+
4
+ ██████╗ ██╗ █████╗ ███╗ ██╗ ██████╗ ██████╗
5
+ ██╔══██╗ ██║██╔══██╗████╗ ██║██╔════╝ ██╔═══██╗
6
+ ██║ ██║ ██║███████║██╔██╗ ██║██║ ███╗██║ ██║
7
+ ██║ ██║██ ██║██╔══██║██║╚██╗██║██║ ██║██║ ██║
8
+ ██████╔╝╚█████╔╝██║ ██║██║ ╚████║╚██████╔╝╚██████╔╝
9
+ ╚═════╝ ╚════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═════╝
10
+
11
+ ███████╗██╗ ██╗███████╗████████╗███████╗███╗ ███╗██████╗
12
+ ██╔════╝╚██╗ ██╔╝██╔════╝╚══██╔══╝██╔════╝████╗ ████║██╔══██╗
13
+ ███████╗ ╚████╔╝ ███████╗ ██║ █████╗ ██╔████╔██║██║ ██║
14
+ ╚════██║ ╚██╔╝ ╚════██║ ██║ ██╔══╝ ██║╚██╔╝██║██║ ██║
15
+ ███████║ ██║ ███████║ ██║ ███████╗██║ ╚═╝ ██║██████╔╝
16
+ ╚══════╝ ╚═╝ ╚══════╝ ╚═╝ ╚══════╝╚═╝ ╚═╝╚═════╝
17
+
18
+ """
19
+
20
+ VERSION = (0, 1, 0)
21
+
22
+ __title__ = "django-systemd"
23
+ __version__ = ".".join(str(i) for i in VERSION)
24
+ __author__ = "Brian Kohan"
25
+ __license__ = "MIT"
26
+ __copyright__ = "Copyright 2026 Brian Kohan"
File without changes
django_systemd/apps.py ADDED
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DjangoSystemdConfig(AppConfig):
5
+ name = "django_systemd"
6
+ verbose_name = "Django Systemd Integration"
@@ -0,0 +1,197 @@
1
+ import logging
2
+ import os
3
+ import re
4
+ import sys
5
+ import typing as t
6
+ from dataclasses import dataclass
7
+ from functools import cache
8
+ from pathlib import Path
9
+
10
+ from render_static.context import resolve_context
11
+ from render_static.engine import StaticTemplateEngine
12
+
13
+ from .defines import SystemdUnitType
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ unit_types = "|".join(re.escape(typ.value) for typ in SystemdUnitType)
18
+
19
+ # Names start with a word character so none can be mistaken for an option.
20
+ SERVICE_UNIT_REGEX = re.compile(rf"^(?P<name>\w[\w.@-]*)\.(?P<type>{unit_types})$")
21
+
22
+ # A deterministic sort key for the order units are invoked and reported in.
23
+ # Sockets sort before the services they activate, paths and timers sort after.
24
+ # Anything not listed sorts last. systemd itself orders the jobs within the
25
+ # transaction; this only makes the invocation and its output reproducible.
26
+ _RESTART_ORDER: dict[SystemdUnitType, int] = {
27
+ SystemdUnitType.SOCKET: 0,
28
+ SystemdUnitType.SERVICE: 1,
29
+ SystemdUnitType.PATH: 2,
30
+ SystemdUnitType.TIMER: 3,
31
+ }
32
+
33
+
34
+ @dataclass
35
+ class ServiceUnit:
36
+ """
37
+ A systemd unit that belongs to this project.
38
+
39
+ :param name: The unit name without its type suffix (e.g. ``web``).
40
+ :param unit_type: The :class:`~django_systemd.defines.SystemdUnitType`.
41
+ :param path: The template (or rendered file) this unit came from, if known.
42
+ :param instanceable: True if this is a template unit (its name ends in ``@``).
43
+ :param template: The template name this unit was discovered under, as the
44
+ render engine knows it (e.g. ``sub/web.service``).
45
+ """
46
+
47
+ name: str
48
+ unit_type: SystemdUnitType
49
+ path: Path | None = None
50
+ instanceable: bool = False
51
+ template: str = ""
52
+
53
+ def __post_init__(self) -> None:
54
+ if not self.template:
55
+ self.template = self.filename
56
+
57
+ @property
58
+ def filename(self) -> str:
59
+ """The unit file name systemd knows this unit by, e.g. ``web.service``."""
60
+ return f"{self.name}.{self.unit_type.value}"
61
+
62
+ @property
63
+ def restart_priority(self) -> int:
64
+ """
65
+ A deterministic sort key for invocation and output order; lower values
66
+ sort first. systemd itself orders the jobs within the transaction.
67
+ """
68
+ return _RESTART_ORDER.get(self.unit_type, len(_RESTART_ORDER))
69
+
70
+ @classmethod
71
+ def parse(cls, raw: Path | str) -> "ServiceUnit":
72
+ """
73
+ Build a :class:`ServiceUnit` from a unit file name or path.
74
+
75
+ :raises ValueError: if the name is not ``<name>.<unit type>``.
76
+ """
77
+ path = raw if isinstance(raw, Path) else None
78
+ name = raw.name if isinstance(raw, Path) else raw
79
+ if mtch := SERVICE_UNIT_REGEX.match(name):
80
+ return cls(
81
+ name=mtch.groupdict()["name"],
82
+ unit_type=SystemdUnitType.from_literal(mtch.groupdict()["type"]),
83
+ path=path,
84
+ instanceable=mtch.groupdict()["name"].endswith("@"),
85
+ )
86
+ raise ValueError(f"Unrecognized unit name: '{name}'")
87
+
88
+
89
+ @cache
90
+ def template_engine_config() -> dict[str, t.Any]:
91
+ """
92
+ Get the configuration for the systemd template rendering engine.
93
+
94
+ :return: The configuration dictionary for the rendering engine.
95
+ :rtype: Dict[str, Any]
96
+ """
97
+ from django.conf import settings
98
+ from django_typer.utils import get_usage_script
99
+
100
+ engine_config = getattr(
101
+ settings,
102
+ "SYSTEMD_TEMPLATE_ENGINE",
103
+ {
104
+ "ENGINES": [
105
+ {
106
+ "BACKEND": "render_static.backends.StaticDjangoTemplates",
107
+ "OPTIONS": {
108
+ "app_dir": "systemd",
109
+ "loaders": [
110
+ "render_static.loaders.StaticAppDirectoriesBatchLoader"
111
+ ],
112
+ "builtins": ["render_static.templatetags.render_static"],
113
+ "autoescape": False,
114
+ },
115
+ }
116
+ ]
117
+ },
118
+ )
119
+ engine_config.setdefault(
120
+ "context", getattr(settings, "SYSTEMD_TEMPLATE_CONTEXT", {})
121
+ )
122
+ engine_config["context"] = resolve_context(engine_config["context"])
123
+ engine_config["context"].setdefault("settings", settings)
124
+ engine_config["context"].setdefault("venv", Path(sys.prefix))
125
+ engine_config["context"].setdefault("python", Path(sys.executable))
126
+ engine_config["context"].setdefault("django-admin", get_usage_script())
127
+ engine_config.setdefault(
128
+ "templates",
129
+ getattr(
130
+ settings,
131
+ "SYSTEMD_TEMPLATES",
132
+ [f"**/*.{unit_type}" for unit_type in SystemdUnitType],
133
+ ),
134
+ )
135
+ engine_config["context"].setdefault(
136
+ "DJANGO_SETTINGS_MODULE", os.environ.get("DJANGO_SETTINGS_MODULE", "")
137
+ )
138
+ return engine_config
139
+
140
+
141
+ @cache
142
+ def render_engine() -> StaticTemplateEngine:
143
+ """
144
+ Get the configured rendering engine for systemd service units.
145
+
146
+ :return: Rendering engine that knows how to find and render systemd service unit
147
+ templates.
148
+ :rtype: :class:`~render_static.engine.StaticTemplateEngine`
149
+ """
150
+ return StaticTemplateEngine(template_engine_config())
151
+
152
+
153
+ def project_units() -> list[ServiceUnit]:
154
+ """
155
+ The manifest: every systemd unit template bundled by an installed app.
156
+
157
+ Templates are those matching the ``SYSTEMD_TEMPLATES`` patterns. The render
158
+ engine resolves each template name to its highest-precedence app and may
159
+ yield that winner once per app that provides the name, so repeats are
160
+ collapsed here by unit file name. Files that match a pattern but are not
161
+ valid ``<name>.<unit type>`` names are skipped with a warning.
162
+
163
+ When two templates produce the same unit file name, the first one
164
+ discovered wins and a warning is logged.
165
+
166
+ :return: Units in discovery order, each with ``path`` set to its template
167
+ file and ``template`` set to the name the render engine knows it by.
168
+ """
169
+ from django.template.exceptions import TemplateDoesNotExist
170
+
171
+ engine = render_engine()
172
+ seen: dict[str, str] = {}
173
+ units: list[ServiceUnit] = []
174
+ for pattern in template_engine_config()["templates"]:
175
+ try:
176
+ for render in engine.find(pattern):
177
+ origin = Path(render.template.origin.name)
178
+ try:
179
+ unit = ServiceUnit.parse(origin)
180
+ except ValueError as err:
181
+ logger.warning("Ignoring %s: %s", origin, err)
182
+ continue
183
+ template_name = render.template.origin.template_name
184
+ if unit.filename in seen:
185
+ logger.warning(
186
+ "Ignoring %s: unit file %s is already provided by template %s",
187
+ origin,
188
+ unit.filename,
189
+ seen[unit.filename],
190
+ )
191
+ continue
192
+ unit.template = template_name
193
+ seen[unit.filename] = template_name
194
+ units.append(unit)
195
+ except TemplateDoesNotExist:
196
+ continue
197
+ return units
@@ -0,0 +1,96 @@
1
+ """
2
+ Enumerations of the values systemd accepts in unit files.
3
+ """
4
+
5
+ from dataclasses import dataclass
6
+ from enum import Enum
7
+ from typing import Self
8
+
9
+
10
+ @dataclass(eq=False, repr=False)
11
+ class SystemdValue:
12
+ """The data every :class:`SystemdEnum` member carries."""
13
+
14
+ literal: str
15
+ """The string systemd uses for this value, e.g. ``service`` or ``on-failure``."""
16
+
17
+ description: str
18
+ """A short human-readable explanation of the value."""
19
+
20
+
21
+ class SystemdEnum(SystemdValue, Enum):
22
+ """
23
+ A dataclass enum whose ``value`` is the literal systemd string.
24
+
25
+ Members convert to and from that string: ``str(member)`` returns it and
26
+ ``SystemdUnitType("service")`` looks a member up by it. Members are not
27
+ ``str`` instances, so compare against other members or ``member.value``.
28
+ """
29
+
30
+ def __new__(cls, literal: str, description: str) -> Self:
31
+ member = object.__new__(cls)
32
+ member._value_ = literal
33
+ return member
34
+
35
+ def __str__(self) -> str:
36
+ return self.literal
37
+
38
+ @classmethod
39
+ def from_literal(cls, literal: str) -> Self:
40
+ """
41
+ Look a member up by its systemd string.
42
+
43
+ Equivalent to ``cls(literal)``, which mypy mis-checks against
44
+ :meth:`__new__`; use this in type-checked code.
45
+
46
+ :raises ValueError: if no member has this literal.
47
+ """
48
+ return cls(literal) # type: ignore[call-arg]
49
+
50
+
51
+ class SystemdUnitType(SystemdEnum):
52
+ """The kinds of systemd unit, named by their file suffix."""
53
+
54
+ # fmt: off
55
+ SERVICE = "service", "Manages system services and daemons, including their startup, shutdown, and runtime behavior."
56
+ SOCKET = "socket", "Implements socket-based activation, starting a service when traffic arrives on a specific socket."
57
+ TARGET = "target", "Groups other units together to define synchronization points or system states (e.g., multi-user.target, graphical.target)"
58
+ TIMER = "timer", "Functions as a cron-like job scheduler, activating a service unit on a real-time or monotonic timer."
59
+ PATH = "path", "Monitors files or directories and can activate a service unit when a change or access occurs."
60
+ MOUNT = "mount", "Manages filesystem mount points."
61
+ AUTOMOUNT = "automount", "Provides on-demand mounting of filesystems, similar to traditional automounters."
62
+ SWAP = "swap", "Manages swap devices and files."
63
+ DEVICE = "device", "Controls access to kernel-recognized devices and can activate other units when a specific device becomes available."
64
+ SCOPE = "scope", "Manages externally created processes that were not started by systemd itself (e.g., user sessions from a login manager)."
65
+ SNAPSHOT = "snapshot", "Saves the current state of the systemd manager and all running units, allowing the system to be restored to that state later."
66
+ SLICE = "slice", "Organizes units into a hierarchical tree for resource management (CPU, memory, etc.) using control groups (cgroups)."
67
+ # fmt: on
68
+
69
+
70
+ class SystemdStartupType(SystemdEnum):
71
+ """Values of ``Type=`` in a ``[Service]`` section."""
72
+
73
+ # fmt: off
74
+ SIMPLE = "simple", "systemd considers the service started immediately after the main process is forked."
75
+ EXEC = "exec", "Similar to simple, but systemd waits until the main service binary has successfully executed before proceeding."
76
+ FORKING = "forking", "For traditional UNIX daemons that fork into the background; systemd waits for the parent process to exit and the child to become the main process."
77
+ ONESHOT = "oneshot", "A service that runs a single command and then exits. Often used with RemainAfterExit=yes for actions that change system state."
78
+ DBUS = "dbus", "The service is considered started when it acquires a specific name on the D-Bus system bus."
79
+ NOTIFY = "notify", "Similar to exec, but the service sends a notification message to systemd when it is ready."
80
+ NOTIFY_RELOAD = "notify-reload", "Similar to notify, but the service also notifies systemd when a reload operation is complete."
81
+ IDLE = "idle", "Delays execution of the service binary until all other active jobs are dispatched, primarily to improve console output readability. "
82
+ # fmt: on
83
+
84
+
85
+ class SystemdRestartType(SystemdEnum):
86
+ """Values of ``Restart=`` in a ``[Service]`` section."""
87
+
88
+ # fmt: off
89
+ NO = "no", "No automatic restarts."
90
+ ON_SUCCESS = "on-success", "Restarts only if the service exits cleanly (exit code 0 or specific signals)."
91
+ ON_FAILURE = "on-failure", "Restarts on non-zero exit code, termination by certain signals, or timeout. This is a common setting for general services."
92
+ ON_ABNORMAL = "on-abnormal", "Restarts if terminated by a signal or timeout, but not for normal error exit."
93
+ ON_WATCHDOG = "on-watchdog", "Restarts only if the watchdog timeout is triggered."
94
+ ON_ABORT = "on-abort", "Restarts on exit due to an uncaught signal not defined as clean."
95
+ ALWAYS = "always", "Restarts regardless of exit status, signal termination, or timeout. "
96
+ # fmt: on
File without changes
File without changes
@@ -0,0 +1,374 @@
1
+ """
2
+ The systemd command is a Django_ :doc:`management command <django:ref/django-admin>`
3
+ that renders, installs, and restarts the systemd units bundled by your project's
4
+ apps. Every subcommand works from the same manifest, the unit templates discovered
5
+ in each installed app's ``systemd/`` directory, so a deployment never has to
6
+ hard-code unit names.
7
+
8
+ All units are managed in the **user** scope (``systemctl --user``). Nothing here
9
+ runs as root.
10
+
11
+ .. typer:: django_systemd.management.commands.systemd.Command:typer_app
12
+ :prog: django-admin systemd
13
+ :width: 80
14
+ :convert-png: latex
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ # Only for subprocess.CalledProcessError; commands run in protocol.py.
20
+ import subprocess # nosec B404
21
+ import tempfile
22
+ from collections.abc import Callable
23
+ from functools import cached_property
24
+ from pathlib import Path
25
+ from typing import Annotated
26
+
27
+ import typer
28
+ from django.core.management import CommandError
29
+ from django.template import TemplateDoesNotExist, TemplateSyntaxError
30
+ from django_typer.management import TyperCommand, command
31
+
32
+ from django_systemd.config import ServiceUnit, project_units, render_engine
33
+ from django_systemd.defines import SystemdUnitType
34
+ from django_systemd.protocol import SubprocessSystemdCtl, SystemdCtl
35
+ from django_systemd.signals import unit_installed
36
+
37
+ ContextOption = Annotated[
38
+ list[str] | None,
39
+ typer.Option(
40
+ "--context",
41
+ "-c",
42
+ help="Override a template context variable as KEY=VALUE. May be repeated.",
43
+ ),
44
+ ]
45
+
46
+ UnitsArgument = Annotated[
47
+ list[str] | None,
48
+ typer.Argument(
49
+ help="Unit file names to act on. Defaults to every installed project unit."
50
+ ),
51
+ ]
52
+
53
+
54
+ def describe_failure(err: subprocess.CalledProcessError) -> str:
55
+ """One line naming the systemctl invocation and why it failed."""
56
+ detail = (err.stderr or "").strip() or f"exit status {err.returncode}"
57
+ return f"{' '.join(err.cmd)} failed: {detail}"
58
+
59
+
60
+ def parse_context(pairs: list[str]) -> dict[str, str]:
61
+ """Turn ``["venv=/srv/app"]`` into ``{"venv": "/srv/app"}``."""
62
+ context: dict[str, str] = {}
63
+ for pair in pairs:
64
+ key, sep, value = pair.partition("=")
65
+ key = key.strip()
66
+ if not sep or not key:
67
+ raise CommandError(f"Context overrides must be KEY=VALUE, got: {pair!r}")
68
+ context[key] = value
69
+ return context
70
+
71
+
72
+ class Command(TyperCommand):
73
+ """
74
+ The ``systemd`` management command: list, render, install, uninstall,
75
+ restart and reload this project's units.
76
+ """
77
+
78
+ @cached_property
79
+ def ctl(self) -> SystemdCtl:
80
+ return SubprocessSystemdCtl()
81
+
82
+ @cached_property
83
+ def units(self) -> list[ServiceUnit]:
84
+ return project_units()
85
+
86
+ def run_ctl(self, verb: Callable[..., None], *args: str) -> None:
87
+ """Run a systemctl-backed verb, surfacing stderr on failure."""
88
+ try:
89
+ verb(*args)
90
+ except subprocess.CalledProcessError as err:
91
+ raise CommandError(describe_failure(err)) from err
92
+
93
+ def require_systemctl(self) -> None:
94
+ """Refuse to proceed when systemctl is not available on this system."""
95
+ if not self.ctl.available:
96
+ raise CommandError("systemctl is not available on this system.")
97
+
98
+ def targets(self, names: list[str]) -> list[ServiceUnit]:
99
+ """
100
+ Resolve unit names to project units.
101
+
102
+ The priority sort only makes the invocation and its output
103
+ deterministic; systemd orders the jobs itself within the transaction.
104
+ Template units (``name@.type``) are never targets because systemctl needs
105
+ an instance name to act on them. With no names, every installed
106
+ non-template unit is selected, except that a service with a timer or
107
+ path unit of the same name is dropped: that service is triggered by
108
+ its timer or path (typically a oneshot job) and restarting it directly
109
+ would run the job, not just make it ready to run. Naming the service
110
+ explicitly still restarts it.
111
+ """
112
+ by_name = {u.filename: u for u in self.units if not u.instanceable}
113
+ template_names = {u.filename for u in self.units if u.instanceable}
114
+ if names:
115
+ templates = [name for name in names if name in template_names]
116
+ if templates:
117
+ raise CommandError(
118
+ f"Template units cannot be restarted directly: {', '.join(templates)}"
119
+ )
120
+ unknown = [name for name in names if name not in by_name]
121
+ if unknown:
122
+ raise CommandError(f"Unknown project unit(s): {', '.join(unknown)}")
123
+ selected = [by_name[n] for n in dict.fromkeys(names)]
124
+ else:
125
+ selected = [
126
+ u for u in by_name.values() if self.ctl.is_installed(u.filename)
127
+ ]
128
+ triggered = {
129
+ u.name
130
+ for u in selected
131
+ if u.unit_type in (SystemdUnitType.TIMER, SystemdUnitType.PATH)
132
+ }
133
+ selected = [
134
+ u
135
+ for u in selected
136
+ if not (u.unit_type is SystemdUnitType.SERVICE and u.name in triggered)
137
+ ]
138
+ return sorted(selected, key=lambda u: u.restart_priority)
139
+
140
+ def render_units(
141
+ self, dest: Path, context: dict[str, str] | None = None
142
+ ) -> list[tuple[ServiceUnit, Path]]:
143
+ """Render every project unit into ``dest`` as ``<dest>/<unit filename>``."""
144
+ if dest.exists() and not dest.is_dir():
145
+ raise CommandError(f"{dest} exists and is not a directory.")
146
+ if not self.units:
147
+ raise CommandError("No systemd unit templates found.")
148
+ dest.mkdir(parents=True, exist_ok=True)
149
+ rendered: list[tuple[ServiceUnit, Path]] = []
150
+ for unit in self.units:
151
+ # Absolute: render-static 3.5 builds a Path from a SafeString, which
152
+ # Python 3.11 rejects for a single relative path part.
153
+ target = dest.absolute() / unit.filename
154
+ try:
155
+ for render in render_engine().render_each(
156
+ unit.template, dest=target, context=context or None
157
+ ):
158
+ rendered.append((unit, Path(render.destination)))
159
+ except (TemplateDoesNotExist, TemplateSyntaxError) as err:
160
+ target.unlink(missing_ok=True)
161
+ raise CommandError(f"Failed to render {unit.template}: {err}") from err
162
+ except BaseException:
163
+ # Anything else (e.g. NoReverseMatch from {% url %}) is a bug in the
164
+ # template or the project and should surface with its traceback.
165
+ target.unlink(missing_ok=True)
166
+ raise
167
+ return rendered
168
+
169
+ @command(name="list")
170
+ def list_units(self) -> None:
171
+ """List this project's systemd units and whether each is installed, enabled and active."""
172
+ if not self.units:
173
+ typer.echo("No systemd unit templates found.")
174
+ return
175
+ width = max(len("UNIT"), *(len(u.filename) for u in self.units))
176
+ typer.echo(
177
+ f"{'UNIT':<{width}} {'INSTALLED':<10} {'ENABLED':<8} {'ACTIVE':<8} SOURCE"
178
+ )
179
+ available = self.ctl.available
180
+ for unit in self.units:
181
+ installed = self.ctl.is_installed(unit.filename)
182
+ enabled = active = "-"
183
+ if installed and available and not unit.instanceable:
184
+ try:
185
+ enabled = "yes" if self.ctl.is_enabled(unit.filename) else "no"
186
+ active = "yes" if self.ctl.is_active(unit.filename) else "no"
187
+ except subprocess.CalledProcessError as err:
188
+ raise CommandError(describe_failure(err)) from err
189
+ typer.echo(
190
+ f"{unit.filename:<{width}} {'yes' if installed else 'no':<10} "
191
+ f"{enabled:<8} {active:<8} {unit.path}"
192
+ )
193
+
194
+ @command()
195
+ def render(
196
+ self,
197
+ output_dir: Annotated[
198
+ Path | None,
199
+ typer.Argument(
200
+ help="Directory to render unit files into. Defaults to the current directory."
201
+ ),
202
+ ] = None,
203
+ context: ContextOption = None,
204
+ ) -> None:
205
+ """Render this project's unit templates to a directory."""
206
+ rendered = self.render_units(
207
+ output_dir or Path("."), parse_context(context or [])
208
+ )
209
+ for _, path in rendered:
210
+ typer.echo(str(path))
211
+
212
+ @command()
213
+ def install(
214
+ self,
215
+ source: Annotated[
216
+ Path | None,
217
+ typer.Option(
218
+ "--source",
219
+ help="Install pre-rendered unit files from this directory instead of rendering now.",
220
+ exists=True,
221
+ file_okay=False,
222
+ ),
223
+ ] = None,
224
+ enable: Annotated[
225
+ bool,
226
+ typer.Option(
227
+ "--enable/--no-enable", help="Enable the units after installing."
228
+ ),
229
+ ] = False,
230
+ context: ContextOption = None,
231
+ ) -> None:
232
+ """
233
+ Install this project's units into the user unit directory.
234
+
235
+ Units are rendered first unless --source points at pre-rendered files.
236
+ Running install again replaces the installed files, so this is also how
237
+ you update units after a deploy.
238
+ """
239
+ if not self.units:
240
+ raise CommandError("No systemd unit templates found.")
241
+ if source is not None and context:
242
+ raise CommandError("--context has no effect with --source.")
243
+
244
+ with tempfile.TemporaryDirectory() as tmp:
245
+ if source is None:
246
+ files = self.render_units(Path(tmp), parse_context(context or []))
247
+ else:
248
+ # Pre-rendered units are flat files named by unit file name, exactly
249
+ # as `systemd render` writes them.
250
+ files = [(unit, source / unit.filename) for unit in self.units]
251
+ missing = [path.name for _, path in files if not path.is_file()]
252
+ if missing:
253
+ raise CommandError(
254
+ f"Missing unit files in {source}: {', '.join(missing)}"
255
+ )
256
+ for unit, path in files:
257
+ try:
258
+ destination = self.ctl.install_unit(path)
259
+ except OSError as err:
260
+ raise CommandError(
261
+ f"Failed to install {unit.filename} to {self.ctl.unit_dir}: {err}. "
262
+ "Re-run install once the cause is fixed."
263
+ ) from err
264
+ unit_installed.send(sender=self, unit=unit, destination=destination)
265
+ typer.echo(str(destination))
266
+
267
+ if not self.ctl.available:
268
+ typer.secho(
269
+ "systemctl not found; skipped daemon-reload and enable.", err=True
270
+ )
271
+ return
272
+ self.run_ctl(self.ctl.daemon_reload)
273
+ if enable:
274
+ for unit in self.units:
275
+ if not unit.instanceable:
276
+ self.run_ctl(self.ctl.enable, unit.filename)
277
+
278
+ @command()
279
+ def uninstall(self) -> None:
280
+ """Stop, disable and remove this project's units from the user unit directory."""
281
+ for unit in self.units:
282
+ if (
283
+ self.ctl.available
284
+ and not unit.instanceable
285
+ and self.ctl.is_installed(unit.filename)
286
+ ):
287
+ for verb in (self.ctl.stop, self.ctl.disable):
288
+ try:
289
+ verb(unit.filename)
290
+ except subprocess.CalledProcessError as err:
291
+ typer.secho(describe_failure(err), err=True)
292
+ try:
293
+ removed = self.ctl.uninstall_unit(unit.filename)
294
+ except OSError as err:
295
+ raise CommandError(
296
+ f"Failed to remove {unit.filename} from {self.ctl.unit_dir}: {err}"
297
+ ) from err
298
+ if removed:
299
+ typer.echo(f"removed {unit.filename}")
300
+ if self.ctl.available:
301
+ self.run_ctl(self.ctl.daemon_reload)
302
+ else:
303
+ typer.secho(
304
+ "systemctl not found; skipped stop, disable and daemon-reload.",
305
+ err=True,
306
+ )
307
+
308
+ @command()
309
+ def restart(self, units: UnitsArgument = None) -> None:
310
+ """
311
+ Restart this project's units in a single systemctl transaction.
312
+
313
+ Restarting sockets and services one at a time does not work: systemd
314
+ refuses to start a socket whose service is still running. Passing every
315
+ target to one systemctl invocation lets systemd order the stops and
316
+ starts itself. A failure reports the whole invocation; systemctl's
317
+ output names the job that failed.
318
+ """
319
+ self.require_systemctl()
320
+ targets = self.targets(units or [])
321
+ if not targets:
322
+ typer.secho("No installed project units to restart.", err=True)
323
+ return
324
+ names = [unit.filename for unit in targets]
325
+ self.run_ctl(self.ctl.restart, *names)
326
+ typer.echo(f"restarted {' '.join(names)}")
327
+
328
+ @command()
329
+ def reload(self, units: UnitsArgument = None) -> None:
330
+ """
331
+ Reload services that support it and are running; restart everything else.
332
+
333
+ Only services can define ExecReload=, and systemctl refuses to reload an
334
+ inactive unit, so anything that is not an active reloadable service is
335
+ restarted instead, in one systemctl transaction. A socket paired with a
336
+ service that reloads in place is left as it is.
337
+ """
338
+ self.require_systemctl()
339
+ targets = self.targets(units or [])
340
+ if not targets:
341
+ typer.secho("No installed project units to reload.", err=True)
342
+ return
343
+ to_reload: list[str] = []
344
+ to_restart: list[ServiceUnit] = []
345
+ for unit in targets:
346
+ name = unit.filename
347
+ if (
348
+ unit.unit_type is SystemdUnitType.SERVICE
349
+ and self.ctl.can_reload(name)
350
+ and self.ctl.is_active(name)
351
+ ):
352
+ to_reload.append(name)
353
+ else:
354
+ to_restart.append(unit)
355
+ # A listening socket whose service is reloaded in place needs no action,
356
+ # and systemd would refuse to restart it while the service runs.
357
+ kept = [
358
+ u
359
+ for u in to_restart
360
+ if u.unit_type is SystemdUnitType.SOCKET
361
+ and f"{u.name}.service" in to_reload
362
+ ]
363
+ to_restart = [u for u in to_restart if u not in kept]
364
+ for unit in kept:
365
+ typer.echo(
366
+ f"kept {unit.filename} listening; {unit.name}.service reloads in place"
367
+ )
368
+ if to_restart:
369
+ names = [u.filename for u in to_restart]
370
+ self.run_ctl(self.ctl.restart, *names)
371
+ typer.echo(f"restarted {' '.join(names)}")
372
+ if to_reload:
373
+ self.run_ctl(self.ctl.reload, *to_reload)
374
+ typer.echo(f"reloaded {' '.join(to_reload)}")
@@ -0,0 +1,219 @@
1
+ """
2
+ A thin, mockable seam over ``systemctl --user`` and the user unit directory.
3
+
4
+ django-systemd assumes every unit it manages runs as the deploying user, never as
5
+ root. There is no system scope and no privilege escalation. Anything that needs
6
+ root belongs in your provisioning tooling, not here.
7
+
8
+ Talking to the user manager from a non-login session (for example over SSH as a
9
+ deploy user) requires lingering to be enabled for that user with
10
+ ``loginctl enable-linger``, or ``XDG_RUNTIME_DIR`` to be set. Failures show up as
11
+ ``Failed to connect to bus`` in the raised CalledProcessError.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import shutil
18
+
19
+ # Running systemctl is this module's purpose; see _systemctl for how it is called.
20
+ import subprocess # nosec B404
21
+ from collections.abc import Sequence
22
+ from dataclasses import dataclass
23
+ from pathlib import Path
24
+ from typing import Protocol, runtime_checkable
25
+
26
+
27
+ def user_unit_dir() -> Path:
28
+ """
29
+ The directory systemd searches for user units that we install into.
30
+
31
+ This is ``$XDG_CONFIG_HOME/systemd/user`` when ``XDG_CONFIG_HOME`` is set,
32
+ otherwise ``~/.config/systemd/user``.
33
+ """
34
+ base = os.environ.get("XDG_CONFIG_HOME")
35
+ root = Path(base) if base else Path.home() / ".config"
36
+ return root / "systemd" / "user"
37
+
38
+
39
+ @dataclass(frozen=True, slots=True)
40
+ class CommandResult:
41
+ """The outcome of one systemctl invocation."""
42
+
43
+ argv: tuple[str, ...]
44
+ returncode: int
45
+ stdout: str
46
+ stderr: str
47
+
48
+
49
+ @runtime_checkable
50
+ class SystemdCtl(Protocol):
51
+ """
52
+ What the :class:`systemd command <django_systemd.management.commands.systemd.Command>`
53
+ needs from systemd. Implement this to swap in a fake for tests or a different
54
+ transport.
55
+ """
56
+
57
+ unit_dir: Path
58
+
59
+ @property
60
+ def available(self) -> bool:
61
+ """
62
+ True if a systemctl binary is on PATH. This does not check that the user
63
+ manager is reachable; callers must check it before calling any other
64
+ systemctl-backed method, which raise FileNotFoundError when systemctl is
65
+ absent. ``is_installed``, ``install_unit`` and ``uninstall_unit`` are
66
+ filesystem-only and do not require this check.
67
+ """
68
+ ...
69
+
70
+ def daemon_reload(self) -> None: ...
71
+ def restart(self, *units: str) -> None: ...
72
+ def reload(self, *units: str) -> None: ...
73
+ def stop(self, unit: str) -> None: ...
74
+ def can_reload(self, unit: str) -> bool:
75
+ """True if the unit defines a reload action (``ExecReload=``)."""
76
+ ...
77
+
78
+ def enable(self, unit: str) -> None: ...
79
+ def disable(self, unit: str) -> None: ...
80
+ def is_active(self, unit: str) -> bool: ...
81
+ def is_enabled(self, unit: str) -> bool: ...
82
+
83
+ def is_installed(self, name: str) -> bool:
84
+ """True if a unit file with this name exists in :attr:`unit_dir`."""
85
+ ...
86
+
87
+ def install_unit(
88
+ self, source: Path, *, name: str | None = None, mode: int = 0o644
89
+ ) -> Path:
90
+ """
91
+ Copy ``source`` into :attr:`unit_dir`, replacing any existing file.
92
+
93
+ :param source: The rendered unit file to install.
94
+ :param name: Install under this file name instead of ``source.name``.
95
+ :param mode: File mode to apply to the installed unit.
96
+ :return: The path of the installed unit file.
97
+ """
98
+ ...
99
+
100
+ def uninstall_unit(self, name: str) -> bool:
101
+ """
102
+ Remove the unit file with this name from :attr:`unit_dir`.
103
+
104
+ :return: True if a file was removed, False if there was nothing to remove.
105
+ """
106
+ ...
107
+
108
+
109
+ class SubprocessSystemdCtl:
110
+ """
111
+ :class:`SystemdCtl` implemented by shelling out to ``systemctl --user``.
112
+
113
+ :param unit_dir: Where to install unit files. Defaults to :func:`user_unit_dir`.
114
+ """
115
+
116
+ # systemctl is-enabled prints one of many states; these all mean "will start".
117
+ _ENABLED_STATES = frozenset(
118
+ {"enabled", "enabled-runtime", "static", "indirect", "alias"}
119
+ )
120
+ # is-active states that mean the unit is up or coming up.
121
+ _ACTIVE_STATES = frozenset({"active", "activating", "reloading"})
122
+
123
+ def __init__(self, unit_dir: Path | None = None) -> None:
124
+ self.unit_dir = unit_dir or user_unit_dir()
125
+
126
+ @property
127
+ def available(self) -> bool:
128
+ return shutil.which("systemctl") is not None
129
+
130
+ def _systemctl(
131
+ self, *args: str, units: Sequence[str] = (), check: bool = True
132
+ ) -> CommandResult:
133
+ # Unit names follow "--" so systemctl never parses one as an option.
134
+ cmd = ["systemctl", "--user", *args, *(("--", *units) if units else ())]
135
+ # An argument list with no shell, a fixed executable and fixed
136
+ # subcommands; unit names are positional after "--".
137
+ result = subprocess.run( # nosec B603
138
+ cmd, capture_output=True, text=True, check=False
139
+ )
140
+ if check and result.returncode != 0:
141
+ raise subprocess.CalledProcessError(
142
+ result.returncode, cmd, result.stdout, result.stderr
143
+ )
144
+ return CommandResult(
145
+ argv=tuple(cmd),
146
+ returncode=result.returncode,
147
+ stdout=result.stdout,
148
+ stderr=result.stderr,
149
+ )
150
+
151
+ def daemon_reload(self) -> None:
152
+ self._systemctl("daemon-reload")
153
+
154
+ def restart(self, *units: str) -> None:
155
+ self._systemctl("restart", units=units)
156
+
157
+ def reload(self, *units: str) -> None:
158
+ self._systemctl("reload", units=units)
159
+
160
+ def stop(self, unit: str) -> None:
161
+ self._systemctl("stop", units=[unit])
162
+
163
+ def can_reload(self, unit: str) -> bool:
164
+ result = self._systemctl(
165
+ "show", "--property=CanReload", "--value", units=[unit], check=False
166
+ )
167
+ return result.stdout.strip() == "yes"
168
+
169
+ def enable(self, unit: str) -> None:
170
+ self._systemctl("enable", units=[unit])
171
+
172
+ def disable(self, unit: str) -> None:
173
+ self._systemctl("disable", units=[unit])
174
+
175
+ def is_active(self, unit: str) -> bool:
176
+ result = self._systemctl("is-active", units=[unit], check=False)
177
+ if result.returncode != 0 and not result.stdout:
178
+ raise subprocess.CalledProcessError(
179
+ result.returncode, result.argv, result.stdout, result.stderr
180
+ )
181
+ return result.stdout.strip() in self._ACTIVE_STATES
182
+
183
+ def is_enabled(self, unit: str) -> bool:
184
+ result = self._systemctl("is-enabled", units=[unit], check=False)
185
+ if result.returncode != 0 and not result.stdout:
186
+ raise subprocess.CalledProcessError(
187
+ result.returncode, result.argv, result.stdout, result.stderr
188
+ )
189
+ return result.stdout.strip() in self._ENABLED_STATES
190
+
191
+ def _unit_path(self, name: str) -> Path:
192
+ if not name or Path(name).name != name:
193
+ raise ValueError(f"Not a bare unit file name: {name!r}")
194
+ return self.unit_dir / name
195
+
196
+ def is_installed(self, name: str) -> bool:
197
+ return self._unit_path(name).is_file()
198
+
199
+ def install_unit(
200
+ self, source: Path, *, name: str | None = None, mode: int = 0o644
201
+ ) -> Path:
202
+ destination = self._unit_path(name if name is not None else source.name)
203
+ self.unit_dir.mkdir(parents=True, exist_ok=True)
204
+ staged = destination.with_name(destination.name + ".tmp")
205
+ try:
206
+ shutil.copyfile(source, staged)
207
+ staged.chmod(mode)
208
+ os.replace(staged, destination)
209
+ except OSError:
210
+ staged.unlink(missing_ok=True)
211
+ raise
212
+ return destination
213
+
214
+ def uninstall_unit(self, name: str) -> bool:
215
+ destination = self._unit_path(name)
216
+ if destination.is_file() or destination.is_symlink():
217
+ destination.unlink()
218
+ return True
219
+ return False
@@ -0,0 +1,25 @@
1
+ """
2
+ All :pypi:`django-systemd` specific :doc:`django:topics/signals` are defined here.
3
+ """
4
+
5
+ from django.dispatch import Signal
6
+
7
+ unit_installed = Signal()
8
+ """
9
+ Sent by ``django-admin systemd install`` after each unit file has been copied into
10
+ the user unit directory, before ``daemon-reload`` runs.
11
+
12
+ **Signature:**
13
+ ``(sender, unit, destination, **kwargs)``
14
+
15
+ :param sender: The running :class:`~django_systemd.management.commands.systemd.Command`
16
+ instance.
17
+ :param unit: The :class:`~django_systemd.config.ServiceUnit` that was installed.
18
+ :param destination: The :class:`~pathlib.Path` of the installed unit file.
19
+
20
+ Receiver exceptions propagate and abort the install, so receivers must not raise
21
+ for conditions they can tolerate.
22
+
23
+ Because the signal fires before ``daemon-reload``, receivers can act on the
24
+ installed file but not yet on the unit through systemctl.
25
+ """
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.5
2
+ Name: django-systemd
3
+ Version: 0.1.0
4
+ Summary: Let your Django apps manage your systemd unit files and services!
5
+ Project-URL: Homepage, https://django-systemd.readthedocs.io
6
+ Project-URL: Documentation, https://django-systemd.readthedocs.io
7
+ Project-URL: Repository, https://github.com/bckohan/django-systemd
8
+ Project-URL: Issues, https://github.com/bckohan/django-systemd/issues
9
+ Project-URL: Changelog, https://django-systemd.readthedocs.io/en/stable/changelog.html
10
+ Project-URL: Code_of_Conduct, https://github.com/bckohan/membership/blob/main/CODE_OF_CONDUCT.md
11
+ Author-email: Brian Kohan <bckohan@gmail.com>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: CLI,Typer,commands,django,integration,management,services,systemd
15
+ Classifier: Development Status :: 5 - Production/Stable
16
+ Classifier: Environment :: Console
17
+ Classifier: Framework :: Django
18
+ Classifier: Framework :: Django :: 5.2
19
+ Classifier: Framework :: Django :: 6.0
20
+ Classifier: Framework :: Django :: 6.1
21
+ Classifier: Intended Audience :: Developers
22
+ Classifier: License :: OSI Approved :: MIT License
23
+ Classifier: Natural Language :: English
24
+ Classifier: Operating System :: OS Independent
25
+ Classifier: Programming Language :: Python
26
+ Classifier: Programming Language :: Python :: 3.11
27
+ Classifier: Programming Language :: Python :: 3.12
28
+ Classifier: Programming Language :: Python :: 3.13
29
+ Classifier: Programming Language :: Python :: 3.14
30
+ Classifier: Programming Language :: Python :: 3.15
31
+ Classifier: Topic :: Internet :: WWW/HTTP
32
+ Classifier: Topic :: Internet :: WWW/HTTP :: Site Management
33
+ Classifier: Topic :: Software Development :: Libraries
34
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
35
+ Requires-Python: <4.0,>=3.11
36
+ Requires-Dist: django-render-static>=3.5.0
37
+ Requires-Dist: django-typer>=3.5.1
38
+ Requires-Dist: django<6.2,>=5.2
39
+ Provides-Extra: rich
40
+ Requires-Dist: rich<16.0.0,>=10.11.0; extra == 'rich'
41
+ Description-Content-Type: text/markdown
42
+
43
+ # django-systemd
44
+
45
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
46
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
47
+ [![PyPI version](https://badge.fury.io/py/django-systemd.svg)](https://pypi.python.org/pypi/django-systemd/)
48
+ [![PyPI pyversions](https://img.shields.io/pypi/pyversions/django-systemd.svg)](https://pypi.python.org/pypi/django-systemd/)
49
+ [![PyPI djversions](https://img.shields.io/pypi/djversions/django-systemd.svg)](https://pypi.org/project/django-systemd/)
50
+ [![PyPI status](https://img.shields.io/pypi/status/django-systemd.svg)](https://pypi.python.org/pypi/django-systemd)
51
+ [![Documentation Status](https://readthedocs.org/projects/django-systemd/badge/?version=latest)](http://django-systemd.readthedocs.io/?badge=latest/)
52
+ [![Code Cov](https://codecov.io/gh/bckohan/django-systemd/branch/main/graph/badge.svg)](https://codecov.io/gh/bckohan/django-systemd)
53
+ [![Test Status](https://github.com/bckohan/django-systemd/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/bckohan/django-systemd/actions/workflows/test.yml?query=branch:main)
54
+ [![Lint Status](https://github.com/bckohan/django-systemd/actions/workflows/lint.yml/badge.svg?branch=main)](https://github.com/bckohan/django-systemd/actions/workflows/lint.yml?query=branch:main)
55
+ [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/bckohan/django-systemd/badge)](https://securityscorecards.dev/viewer/?uri=github.com/bckohan/django-systemd)
56
+
57
+ `django-systemd` does two independent things for a Django deployment:
58
+
59
+ 1. **Generate systemd unit files.** Apps bundle unit templates in a `systemd/`
60
+ directory. Render them at package time with known settings and commit the
61
+ result, or render them at deploy time from live production settings.
62
+ 2. **Manage the project's units.** `django-admin systemd` can list, install,
63
+ update, restart and reload every unit the project defines, without you
64
+ naming them. Everything runs in the user scope via `systemctl --user`; nothing
65
+ runs as root.
66
+
67
+ ```bash
68
+ django-admin systemd list
69
+ django-admin systemd render ./units --context venv=/srv/app/.venv # in CI
70
+ django-admin systemd install --enable # on the host
71
+ django-admin systemd reload # on the host
72
+ ```
73
+
74
+ See the [documentation](https://django-systemd.readthedocs.io) for the how-to and settings.
@@ -0,0 +1,14 @@
1
+ django_systemd/__init__.py,sha256=pHdTt2-eDyfxaJnXRHaegBC6G_4NSgBEngL0y9035IA,2064
2
+ django_systemd/admin.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ django_systemd/apps.py,sha256=jT0aeLpEglqiVX3KIr8hH5QY0uOJ0ujv_CV3ZcejdSo,150
4
+ django_systemd/config.py,sha256=fiXuB4NRjDWDv15wdE6KtoPL_dW5c7dKsHs5Sx7J0L8,7124
5
+ django_systemd/defines.py,sha256=PJtu9gYgS5JJgkY2tiSv794GGPpCZvwjqjRzh7roWIo,5178
6
+ django_systemd/protocol.py,sha256=QPZ8bAc8xGPFfs1tBE6YBDQzvG_gh0L0YQ5EhL2qWsE,7784
7
+ django_systemd/signals.py,sha256=cimplA7O4FEzURrp2rHmDYk4BIT0sqoGHrt0IH_m-wk,869
8
+ django_systemd/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ django_systemd/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ django_systemd/management/commands/systemd.py,sha256=w3KgPqagrHotzNW0kdOmA1mT_khaQTN9xSi9jOnVpi8,15133
11
+ django_systemd-0.1.0.dist-info/METADATA,sha256=JAFozrxQdJ_Dz4NSbgMO5ircY0cTV5ansa5SOAeVQik,4427
12
+ django_systemd-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
13
+ django_systemd-0.1.0.dist-info/licenses/LICENSE,sha256=Kzd8oJVZMXVAjtVE565y3e859cuHZVPgU2UBVp4UrTk,1068
14
+ django_systemd-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brian Kohan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.