loft-cli-core 0.6.3__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.
Files changed (41) hide show
  1. loft_cli_core/__init__.py +1 -0
  2. loft_cli_core/agent_models.py +34 -0
  3. loft_cli_core/agent_paths.py +27 -0
  4. loft_cli_core/plan/__init__.py +0 -0
  5. loft_cli_core/plan/models.py +80 -0
  6. loft_cli_core/plan/render_diff.py +112 -0
  7. loft_cli_core/plan/render_markdown.py +189 -0
  8. loft_cli_core/plan/render_text.py +86 -0
  9. loft_cli_core/policy.py +218 -0
  10. loft_cli_core/registry/__init__.py +108 -0
  11. loft_cli_core/registry/executors.py +31 -0
  12. loft_cli_core/registry/hooks.py +46 -0
  13. loft_cli_core/registry/local_paths.py +147 -0
  14. loft_cli_core/registry/normalizers.py +21 -0
  15. loft_cli_core/registry/planners.py +21 -0
  16. loft_cli_core/registry/resolvers.py +65 -0
  17. loft_cli_core/registry/specs.py +20 -0
  18. loft_cli_core/registry/validators.py +21 -0
  19. loft_cli_core/specs/__init__.py +0 -0
  20. loft_cli_core/specs/backup_job_schema.py +95 -0
  21. loft_cli_core/specs/bootstrap_schema.py +124 -0
  22. loft_cli_core/specs/compose_project_schema.py +93 -0
  23. loft_cli_core/specs/file_template_schema.py +64 -0
  24. loft_cli_core/specs/http_check_schema.py +64 -0
  25. loft_cli_core/specs/loader.py +250 -0
  26. loft_cli_core/specs/postgres_ensure_schema.py +104 -0
  27. loft_cli_core/specs/service_schema.py +114 -0
  28. loft_cli_core/specs/stack_schema.py +74 -0
  29. loft_cli_core/specs/systemd_timer_schema.py +76 -0
  30. loft_cli_core/specs/systemd_unit_schema.py +86 -0
  31. loft_cli_core/specs/validators.py +755 -0
  32. loft_cli_core/state.py +31 -0
  33. loft_cli_core/utils/__init__.py +0 -0
  34. loft_cli_core/utils/files.py +41 -0
  35. loft_cli_core/utils/hashing.py +10 -0
  36. loft_cli_core/utils/os_detect.py +36 -0
  37. loft_cli_core/utils/templates.py +87 -0
  38. loft_cli_core-0.6.3.dist-info/METADATA +10 -0
  39. loft_cli_core-0.6.3.dist-info/RECORD +41 -0
  40. loft_cli_core-0.6.3.dist-info/WHEEL +5 -0
  41. loft_cli_core-0.6.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,250 @@
1
+ """Load and parse YAML specs into typed Pydantic models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import yaml
11
+
12
+ # Matches ${...} tokens — the full token including optional prefix and default.
13
+ _ENV_PATTERN = re.compile(r"\$\{([^}]+)\}")
14
+
15
+
16
+ class SpecLoadError(Exception):
17
+ """Raised when a spec file cannot be loaded or parsed."""
18
+
19
+
20
+ def load_env_file(path: Path) -> dict[str, str]:
21
+ """Load a .env file and return a dict of variable name → value.
22
+
23
+ Supports:
24
+ - Lines of the form ``KEY=VALUE`` or ``KEY="VALUE"`` / ``KEY='VALUE'``
25
+ - ``export KEY=VALUE``
26
+ - Comments (lines starting with ``#``)
27
+ - Blank lines (ignored)
28
+
29
+ Does NOT modify ``os.environ``; the caller is responsible for that.
30
+ """
31
+ env: dict[str, str] = {}
32
+ text = path.read_text(encoding="utf-8")
33
+ for _lineno, raw_line in enumerate(text.splitlines(), 1):
34
+ line = raw_line.strip()
35
+ if not line or line.startswith("#"):
36
+ continue
37
+ # Strip optional 'export ' prefix
38
+ if line.startswith("export "):
39
+ line = line[len("export ") :]
40
+ if "=" not in line:
41
+ continue
42
+ key, _, value = line.partition("=")
43
+ key = key.strip()
44
+ value = value.strip()
45
+ # Strip matching quotes
46
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
47
+ value = value[1:-1]
48
+ env[key] = value
49
+ return env
50
+
51
+
52
+ def _resolve_values(obj: Any, *, strict: bool = True, _path: str = "") -> Any:
53
+ """Recursively resolve ``${[prefix:]key[:-default]}`` tokens in a YAML structure.
54
+
55
+ Token syntax
56
+ ------------
57
+ ``${VAR}``
58
+ Bare reference — shorthand for ``${env:VAR}``. Permanent backward
59
+ compat; will never be deprecated.
60
+
61
+ ``${env:VAR}``
62
+ Explicit environment variable lookup via the ``env`` resolver.
63
+
64
+ ``${file:/path/to/file}``
65
+ Read file contents via the built-in ``file`` resolver.
66
+
67
+ ``${prefix:key}``
68
+ Dispatch to an addon-registered resolver (e.g. ``sops``, ``vault``).
69
+
70
+ ``${VAR:-default}``
71
+ Use *default* if the resolved value is ``None`` (key not found).
72
+ Works with any prefix: ``${env:VAR:-fallback}``,
73
+ ``${file:/opt/key.pub:-}`` etc.
74
+
75
+ Parameters
76
+ ----------
77
+ obj:
78
+ The parsed YAML data (nested dicts, lists, scalars).
79
+ strict:
80
+ When ``True`` (default), raise :class:`SpecLoadError` if a token
81
+ cannot be resolved and has no default value. When ``False``
82
+ ("passthrough"), leave the ``${...}`` token unchanged.
83
+ _path:
84
+ Internal — tracks the YAML field path for error messages.
85
+ """
86
+ if isinstance(obj, str):
87
+ # Import lazily so this function stays usable before load_addons() runs.
88
+ from loft_cli_core.registry.resolvers import get_resolver, list_resolvers
89
+
90
+ def replace(m: re.Match) -> str:
91
+ token = m.group(1)
92
+ location = f" in field '{_path}'" if _path else ""
93
+
94
+ # 1. Split off default value (shell convention: :-)
95
+ if ":-" in token:
96
+ ref_part, default = token.split(":-", 1)
97
+ else:
98
+ ref_part, default = token, None
99
+
100
+ # 2. Extract prefix (first colon in ref_part).
101
+ # No colon → bare ${VAR} → permanent shorthand for ${env:VAR}.
102
+ if ":" in ref_part:
103
+ prefix, key = ref_part.split(":", 1)
104
+ else:
105
+ prefix, key = "env", ref_part
106
+
107
+ # 3. Resolve via registry.
108
+ resolver = get_resolver(prefix)
109
+ if resolver is None:
110
+ known = ", ".join(list_resolvers()) or "none"
111
+ raise SpecLoadError(
112
+ f"Unknown resolver '{prefix}' in '${{{token}}}'{location}. "
113
+ f"Registered resolvers: {known}. "
114
+ f"Is an addon missing?"
115
+ )
116
+
117
+ val = resolver(key)
118
+
119
+ # 4. Value found — return it.
120
+ if val is not None:
121
+ return val
122
+
123
+ # 5. Value not found — try default.
124
+ if default is not None:
125
+ return default
126
+
127
+ # 6. No default — strict vs passthrough.
128
+ if strict:
129
+ raise SpecLoadError(
130
+ f"Unresolved variable '${{{token}}}'{location}: "
131
+ f"resolver '{prefix}' returned no value for key '{key}'"
132
+ )
133
+ return m.group(0) # passthrough: leave ${...} unchanged
134
+
135
+ return _ENV_PATTERN.sub(replace, obj)
136
+ elif isinstance(obj, dict):
137
+ return {
138
+ k: _resolve_values(v, strict=strict, _path=f"{_path}.{k}" if _path else k)
139
+ for k, v in obj.items()
140
+ }
141
+ elif isinstance(obj, list):
142
+ return [
143
+ _resolve_values(item, strict=strict, _path=f"{_path}[{i}]")
144
+ for i, item in enumerate(obj)
145
+ ]
146
+ return obj
147
+
148
+
149
+ # Keep the old name available so any code that imported _resolve_env_vars
150
+ # directly (e.g. existing tests) continues to work without change.
151
+ _resolve_env_vars = _resolve_values
152
+
153
+
154
+ def load_spec(
155
+ path: Path,
156
+ *,
157
+ strict_env: bool = True,
158
+ env_file: Path | None = None,
159
+ env_files: list[Path] | None = None,
160
+ ) -> Any:
161
+ """Load and parse a YAML spec file into a typed model.
162
+
163
+ Parameters
164
+ ----------
165
+ path:
166
+ Path to the YAML spec file.
167
+ strict_env:
168
+ When True (default), unresolved ``${...}`` references raise an error.
169
+ When False, they are left unchanged (passthrough mode).
170
+ env_file:
171
+ Optional path to a single ``.env`` file (backward-compatible).
172
+ env_files:
173
+ Optional list of ``.env`` file paths. Files are loaded in order;
174
+ later files override earlier ones, but existing ``os.environ``
175
+ values always take precedence. When both ``env_file`` and
176
+ ``env_files`` are provided, ``env_file`` is prepended to the list.
177
+ """
178
+ # Ensure built-in and addon kinds are registered (idempotent).
179
+ from loft_cli_core.registry import get_spec_model, list_spec_kinds, load_addons
180
+
181
+ load_addons()
182
+
183
+ if not path.exists():
184
+ raise SpecLoadError(f"Spec file not found: {path}")
185
+
186
+ # Build the ordered list of env files (RFC 008: overlay layering).
187
+ all_env_files: list[Path] = []
188
+ if env_file is not None:
189
+ all_env_files.append(env_file)
190
+ if env_files:
191
+ all_env_files.extend(env_files)
192
+
193
+ # Load env files in order: later files override earlier, but existing
194
+ # os.environ values always take precedence.
195
+ merged_env: dict[str, str] = {}
196
+ for ef in all_env_files:
197
+ if not ef.exists():
198
+ raise SpecLoadError(f"Env file not found: {ef}")
199
+ merged_env.update(load_env_file(ef))
200
+ for key, value in merged_env.items():
201
+ os.environ.setdefault(key, value)
202
+
203
+ text = path.read_text(encoding="utf-8")
204
+
205
+ # Support multiple YAML documents separated by ---
206
+ try:
207
+ documents = list(yaml.safe_load_all(text))
208
+ except yaml.YAMLError as e:
209
+ raise SpecLoadError(f"YAML parse error in {path}: {e}") from e
210
+
211
+ # Filter out empty documents (e.g. trailing ---)
212
+ documents = [d for d in documents if d is not None]
213
+
214
+ if not documents:
215
+ raise SpecLoadError(f"Spec file is empty: {path}")
216
+
217
+ specs = []
218
+ for doc_idx, raw in enumerate(documents):
219
+ if not isinstance(raw, dict):
220
+ raise SpecLoadError(
221
+ f"Document {doc_idx + 1} in {path} must be a YAML mapping, "
222
+ f"got {type(raw).__name__}"
223
+ )
224
+
225
+ kind = raw.get("kind")
226
+ model_class = get_spec_model(kind)
227
+ if model_class is None:
228
+ known = ", ".join(list_spec_kinds()) or "none"
229
+ raise SpecLoadError(
230
+ f"Unknown spec kind '{kind}' in document {doc_idx + 1}. Supported: {known}"
231
+ )
232
+
233
+ try:
234
+ data = _resolve_values(raw, strict=strict_env)
235
+ except SpecLoadError:
236
+ raise
237
+
238
+ try:
239
+ specs.append(model_class.model_validate(data))
240
+ except Exception as e:
241
+ if type(e).__name__ == "ValidationError":
242
+ raise SpecLoadError(
243
+ f"Spec validation error in {path} (document {doc_idx + 1}):\n{e}"
244
+ ) from e
245
+ raise
246
+
247
+ # Return single spec for backward compatibility, list for multi-doc
248
+ if len(specs) == 1:
249
+ return specs[0]
250
+ return specs
@@ -0,0 +1,104 @@
1
+ """Pydantic v2 models for kind: postgres_ensure YAML specs.
2
+
3
+ Ensure PostgreSQL resources exist on a running instance (container via
4
+ docker exec or host/port). Structured declarations only: users,
5
+ databases, extensions, grants. Every action appears as a discrete,
6
+ reviewable plan step. No arbitrary SQL passthrough.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Literal
12
+
13
+ from pydantic import BaseModel, ConfigDict, Field
14
+
15
+ from loft_cli_core.specs.bootstrap_schema import (
16
+ CheckBlock,
17
+ HostBlock,
18
+ InventoryBlock,
19
+ MetaBlock,
20
+ )
21
+
22
+
23
+ class PgConnection(BaseModel):
24
+ """Connection parameters for the PostgreSQL instance."""
25
+
26
+ model_config = ConfigDict(extra="forbid")
27
+
28
+ host: str = "localhost"
29
+ port: int = 5432
30
+ admin_user: str = "postgres"
31
+ docker_exec: str | None = None # container name for docker exec
32
+
33
+
34
+ class PgUser(BaseModel):
35
+ """A PostgreSQL user/role to ensure exists."""
36
+
37
+ model_config = ConfigDict(extra="forbid")
38
+
39
+ name: str
40
+ password_env: str | None = None # env var holding password (resolved at plan time)
41
+
42
+
43
+ class PgDatabase(BaseModel):
44
+ """A PostgreSQL database to ensure exists."""
45
+
46
+ model_config = ConfigDict(extra="forbid")
47
+
48
+ name: str
49
+ owner: str = "postgres"
50
+
51
+
52
+ class PgExtension(BaseModel):
53
+ """A PostgreSQL extension to ensure is installed."""
54
+
55
+ model_config = ConfigDict(extra="forbid")
56
+
57
+ name: str
58
+ database: str
59
+
60
+
61
+ class PgGrant(BaseModel):
62
+ """A PostgreSQL privilege grant."""
63
+
64
+ model_config = ConfigDict(extra="forbid")
65
+
66
+ privilege: str # ALL, SELECT, INSERT, etc.
67
+ on_database: str
68
+ to_user: str
69
+
70
+
71
+ class PostgresEnsureLoginBlock(BaseModel):
72
+ """Login defaults matching post-bootstrap convention (admin@2222)."""
73
+
74
+ model_config = ConfigDict(extra="forbid")
75
+
76
+ user: str = "admin"
77
+ private_key: str = "~/.ssh/id_ed25519"
78
+ password: str | None = None
79
+ port: int = 2222
80
+
81
+
82
+ class PostgresEnsureLocalBlock(BaseModel):
83
+ model_config = ConfigDict(extra="forbid")
84
+
85
+ state_dir: str = ""
86
+ inventory: InventoryBlock = Field(default_factory=InventoryBlock)
87
+
88
+
89
+ class PostgresEnsureSpec(BaseModel):
90
+ """Spec for ensuring PostgreSQL resources exist on a running instance."""
91
+
92
+ model_config = ConfigDict(extra="forbid")
93
+
94
+ kind: Literal["postgres_ensure"]
95
+ meta: MetaBlock
96
+ host: HostBlock
97
+ login: PostgresEnsureLoginBlock = Field(default_factory=PostgresEnsureLoginBlock)
98
+ connection: PgConnection = Field(default_factory=PgConnection)
99
+ users: list[PgUser] = Field(default_factory=list)
100
+ databases: list[PgDatabase] = Field(default_factory=list)
101
+ extensions: list[PgExtension] = Field(default_factory=list)
102
+ grants: list[PgGrant] = Field(default_factory=list)
103
+ local: PostgresEnsureLocalBlock = Field(default_factory=PostgresEnsureLocalBlock)
104
+ checks: list[CheckBlock] = Field(default_factory=list)
@@ -0,0 +1,114 @@
1
+ """Pydantic v2 models for kind: service YAML specs (RFC section 8)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from pydantic import BaseModel, ConfigDict, Field
8
+
9
+ from loft_cli_core.specs.bootstrap_schema import (
10
+ CheckBlock,
11
+ HostBlock,
12
+ InventoryBlock,
13
+ MetaBlock,
14
+ )
15
+
16
+
17
+ class ServiceLoginBlock(BaseModel):
18
+ model_config = ConfigDict(extra="forbid")
19
+
20
+ user: str = "admin"
21
+ private_key: str = "~/.ssh/id_ed25519"
22
+ password: str | None = None
23
+ port: int = 2222
24
+
25
+
26
+ class CreateRoleBlock(BaseModel):
27
+ model_config = ConfigDict(extra="forbid")
28
+
29
+ name: str
30
+ password_env: str = ""
31
+
32
+
33
+ class CreateDatabaseBlock(BaseModel):
34
+ model_config = ConfigDict(extra="forbid")
35
+
36
+ name: str
37
+ owner: str = ""
38
+
39
+
40
+ class PostgresBlock(BaseModel):
41
+ model_config = ConfigDict(extra="forbid")
42
+
43
+ enabled: bool = True
44
+ version: str = "16"
45
+ listen_addresses: list[str] = Field(default_factory=lambda: ["127.0.0.1"])
46
+ create_role: CreateRoleBlock | None = None
47
+ create_database: CreateDatabaseBlock | None = None
48
+
49
+
50
+ class NginxSiteBlock(BaseModel):
51
+ model_config = ConfigDict(extra="forbid")
52
+
53
+ domain: str
54
+ upstream: str = ""
55
+ upstream_port: int = 8080
56
+ listen_port: int = 80
57
+ ssl: bool = False
58
+ ssl_certificate: str = ""
59
+ ssl_certificate_key: str = ""
60
+
61
+
62
+ class NginxBlock(BaseModel):
63
+ model_config = ConfigDict(extra="forbid")
64
+
65
+ enabled: bool = True
66
+ sites: list[NginxSiteBlock] = Field(default_factory=list)
67
+
68
+
69
+ class DockerBlock(BaseModel):
70
+ model_config = ConfigDict(extra="forbid")
71
+
72
+ enabled: bool = True
73
+
74
+
75
+ class HealthCheckBlock(BaseModel):
76
+ model_config = ConfigDict(extra="forbid")
77
+
78
+ type: str = "http"
79
+ url: str = ""
80
+ expect_status: int = 200
81
+
82
+
83
+ class ContainerBlock(BaseModel):
84
+ model_config = ConfigDict(extra="forbid")
85
+
86
+ name: str
87
+ image: str
88
+ ports: list[str] = Field(default_factory=list)
89
+ env: dict[str, str] = Field(default_factory=dict)
90
+ env_file: str | None = None
91
+ restart: str = "unless-stopped"
92
+ healthcheck: HealthCheckBlock | None = None
93
+
94
+
95
+ class ServiceLocalBlock(BaseModel):
96
+ model_config = ConfigDict(extra="forbid")
97
+
98
+ state_dir: str = ""
99
+ inventory: InventoryBlock = Field(default_factory=InventoryBlock)
100
+
101
+
102
+ class ServiceSpec(BaseModel):
103
+ model_config = ConfigDict(extra="forbid")
104
+
105
+ kind: Literal["service"]
106
+ meta: MetaBlock
107
+ host: HostBlock
108
+ login: ServiceLoginBlock = Field(default_factory=ServiceLoginBlock)
109
+ postgres: PostgresBlock | None = None
110
+ nginx: NginxBlock | None = None
111
+ docker: DockerBlock | None = None
112
+ containers: list[ContainerBlock] = Field(default_factory=list)
113
+ local: ServiceLocalBlock = Field(default_factory=ServiceLocalBlock)
114
+ checks: list[CheckBlock] = Field(default_factory=list)
@@ -0,0 +1,74 @@
1
+ """Pydantic v2 models for kind: stack YAML specs.
2
+
3
+ A stack groups related resources (file_template, compose_project, etc.)
4
+ into a single deployable application boundary. Stack members are
5
+ declared inline and executed in dependency order.
6
+
7
+ Design principles
8
+ -----------------
9
+ - Stacks expand into normal resource steps during planning.
10
+ - Operators still see the final concrete plan (no opaque magic bundles).
11
+ - Circular dependencies are rejected at validation time.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from typing import Literal
17
+
18
+ from pydantic import BaseModel, ConfigDict, Field
19
+
20
+ from loft_cli_core.specs.bootstrap_schema import (
21
+ CheckBlock,
22
+ HostBlock,
23
+ InventoryBlock,
24
+ MetaBlock,
25
+ )
26
+
27
+
28
+ class StackLoginBlock(BaseModel):
29
+ """Login defaults matching post-bootstrap convention (admin@2222)."""
30
+
31
+ model_config = ConfigDict(extra="forbid")
32
+
33
+ user: str = "admin"
34
+ private_key: str = "~/.ssh/id_ed25519"
35
+ password: str | None = None
36
+ port: int = 2222
37
+
38
+
39
+ class StackLocalBlock(BaseModel):
40
+ model_config = ConfigDict(extra="forbid")
41
+
42
+ state_dir: str = ""
43
+ inventory: InventoryBlock = Field(default_factory=InventoryBlock)
44
+
45
+
46
+ class StackResourceBlock(BaseModel):
47
+ """A single resource within a stack.
48
+
49
+ Each resource references a spec kind (file_template, compose_project,
50
+ etc.) and carries its kind-specific configuration inline. Optional
51
+ ``depends_on`` declares ordering dependencies between resources in
52
+ the same stack.
53
+ """
54
+
55
+ model_config = ConfigDict(extra="forbid")
56
+
57
+ name: str # unique within the stack, e.g. "traefik-config"
58
+ kind: str # the spec kind: "file_template", "compose_project", etc.
59
+ config: dict = Field(default_factory=dict) # kind-specific config block
60
+ depends_on: list[str] = Field(default_factory=list) # other resource names
61
+
62
+
63
+ class StackSpec(BaseModel):
64
+ """Spec for deploying a stack of related resources on a single host."""
65
+
66
+ model_config = ConfigDict(extra="forbid")
67
+
68
+ kind: Literal["stack"]
69
+ meta: MetaBlock
70
+ host: HostBlock
71
+ login: StackLoginBlock = Field(default_factory=StackLoginBlock)
72
+ local: StackLocalBlock = Field(default_factory=StackLocalBlock)
73
+ resources: list[StackResourceBlock] = Field(default_factory=list)
74
+ checks: list[CheckBlock] = Field(default_factory=list)
@@ -0,0 +1,76 @@
1
+ """Pydantic v2 models for kind: systemd_timer YAML specs.
2
+
3
+ Deploy scheduled execution via systemd timers. The planner generates
4
+ both a .timer and a companion .service (Type=oneshot) unit file, writes
5
+ them to /etc/systemd/system/, and runs daemon-reload + enable --now.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Literal
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+ from loft_cli_core.specs.bootstrap_schema import (
15
+ CheckBlock,
16
+ HostBlock,
17
+ InventoryBlock,
18
+ MetaBlock,
19
+ )
20
+
21
+
22
+ class TimerConfig(BaseModel):
23
+ """Configuration for the systemd timer unit."""
24
+
25
+ model_config = ConfigDict(extra="forbid")
26
+
27
+ timer_name: str # name (without .timer suffix)
28
+ description: str = ""
29
+ on_calendar: str # systemd calendar expression, e.g. "*-*-* 02:00:00"
30
+ persistent: bool = True # run missed events on boot
31
+ accuracy_sec: str = "1min"
32
+
33
+
34
+ class TimerServiceConfig(BaseModel):
35
+ """Configuration for the oneshot service triggered by the timer."""
36
+
37
+ model_config = ConfigDict(extra="forbid")
38
+
39
+ exec_start: str # command to run
40
+ user: str = "root"
41
+ group: str = "root"
42
+ working_directory: str | None = None
43
+ environment: dict[str, str] = Field(default_factory=dict)
44
+
45
+
46
+ class SystemdTimerLoginBlock(BaseModel):
47
+ """Login defaults matching post-bootstrap convention (admin@2222)."""
48
+
49
+ model_config = ConfigDict(extra="forbid")
50
+
51
+ user: str = "admin"
52
+ private_key: str = "~/.ssh/id_ed25519"
53
+ password: str | None = None
54
+ port: int = 2222
55
+
56
+
57
+ class SystemdTimerLocalBlock(BaseModel):
58
+ model_config = ConfigDict(extra="forbid")
59
+
60
+ state_dir: str = ""
61
+ inventory: InventoryBlock = Field(default_factory=InventoryBlock)
62
+
63
+
64
+ class SystemdTimerSpec(BaseModel):
65
+ """Spec for deploying scheduled execution via systemd timers."""
66
+
67
+ model_config = ConfigDict(extra="forbid")
68
+
69
+ kind: Literal["systemd_timer"]
70
+ meta: MetaBlock
71
+ host: HostBlock
72
+ login: SystemdTimerLoginBlock = Field(default_factory=SystemdTimerLoginBlock)
73
+ timer: TimerConfig
74
+ service: TimerServiceConfig
75
+ local: SystemdTimerLocalBlock = Field(default_factory=SystemdTimerLocalBlock)
76
+ checks: list[CheckBlock] = Field(default_factory=list)
@@ -0,0 +1,86 @@
1
+ """Pydantic v2 models for kind: systemd_unit YAML specs.
2
+
3
+ Deploy and manage host-native systemd services. The planner generates
4
+ a complete .service unit file from structured declarations, writes it
5
+ to /etc/systemd/system/, and runs daemon-reload + enable + start.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Literal
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+ from loft_cli_core.specs.bootstrap_schema import (
15
+ CheckBlock,
16
+ HostBlock,
17
+ InventoryBlock,
18
+ MetaBlock,
19
+ )
20
+
21
+
22
+ class SystemdUnitConfig(BaseModel):
23
+ """Configuration for a systemd service unit."""
24
+
25
+ model_config = ConfigDict(extra="forbid")
26
+
27
+ unit_name: str # service name (without .service suffix)
28
+ description: str = ""
29
+ exec_start: str # command to run
30
+ exec_stop: str | None = None
31
+ working_directory: str | None = None
32
+ user: str = "root"
33
+ group: str = "root"
34
+ restart: str = "on-failure" # no, always, on-failure, on-abnormal
35
+ restart_sec: int = 5
36
+ after: list[str] = Field(default_factory=lambda: ["network.target"])
37
+ environment: dict[str, str] = Field(default_factory=dict)
38
+ environment_file: str | None = None
39
+ type: str = "simple" # simple, forking, oneshot, notify
40
+ wanted_by: str = "multi-user.target"
41
+
42
+
43
+ class LogRotateConfig(BaseModel):
44
+ """Optional logrotate configuration for the service."""
45
+
46
+ model_config = ConfigDict(extra="forbid")
47
+
48
+ enabled: bool = False
49
+ path: str = "" # log file path pattern (e.g. /var/log/myapp/*.log)
50
+ rotate: int = 7
51
+ frequency: str = "daily" # daily, weekly, monthly
52
+ compress: bool = True
53
+ max_size: str = "" # e.g. "100M" — rotate when log exceeds this size
54
+
55
+
56
+ class SystemdUnitLoginBlock(BaseModel):
57
+ """Login defaults matching post-bootstrap convention (admin@2222)."""
58
+
59
+ model_config = ConfigDict(extra="forbid")
60
+
61
+ user: str = "admin"
62
+ private_key: str = "~/.ssh/id_ed25519"
63
+ password: str | None = None
64
+ port: int = 2222
65
+
66
+
67
+ class SystemdUnitLocalBlock(BaseModel):
68
+ model_config = ConfigDict(extra="forbid")
69
+
70
+ state_dir: str = ""
71
+ inventory: InventoryBlock = Field(default_factory=InventoryBlock)
72
+
73
+
74
+ class SystemdUnitSpec(BaseModel):
75
+ """Spec for deploying and managing a host-native systemd service."""
76
+
77
+ model_config = ConfigDict(extra="forbid")
78
+
79
+ kind: Literal["systemd_unit"]
80
+ meta: MetaBlock
81
+ host: HostBlock
82
+ login: SystemdUnitLoginBlock = Field(default_factory=SystemdUnitLoginBlock)
83
+ unit: SystemdUnitConfig
84
+ logrotate: LogRotateConfig | None = None
85
+ local: SystemdUnitLocalBlock = Field(default_factory=SystemdUnitLocalBlock)
86
+ checks: list[CheckBlock] = Field(default_factory=list)