-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbase.py
More file actions
280 lines (237 loc) · 8.15 KB
/
Copy pathbase.py
File metadata and controls
280 lines (237 loc) · 8.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/env python3
# Copyright 2025 Canonical Ltd.
# See LICENSE file for licensing details.
"""Base interface for common workload operations."""
import pathlib
from abc import ABC, abstractmethod
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
import tomli
from charmlibs import pathops
from charmlibs.pathops import PathProtocol
from ops import ModelError
from ops.pebble import Error as PebbleError
from single_kernel_postgresql.config.exceptions import PostgreSQLFileOperationError
from single_kernel_postgresql.config.literals import DIR_PERMISSIONS_READONLY
from single_kernel_postgresql.workload.paths.base import Paths
# --- Base Workload
class BaseWorkload(ABC):
"""Base interface for common workload operations."""
def __init__(self, charm_dir: Path):
"""Initialize K8s workload.
Args:
charm_dir: the path to charm code.
"""
super().__init__()
self.charm_dir = charm_dir
@property
@abstractmethod
def root(self) -> PathProtocol:
"""Return the root path."""
pass
@property
@abstractmethod
def user(self) -> str:
"""The OS user that owns workload files (substrate-specific)."""
pass
@property
@abstractmethod
def group(self) -> str:
"""The OS group that owns workload files (substrate-specific)."""
pass
@property
def tls_file_mode(self) -> int:
"""File mode for TLS material written to disk.
Defaults to 0o600 (VM); K8s overrides to 0o400 to match the
pre-migration charm.
"""
return 0o600
@abstractmethod
def install(self) -> None:
"""Install the workload."""
pass
@property
@abstractmethod
def paths(self) -> Paths:
"""Return the Workload's paths."""
pass
@property
@abstractmethod
def workload_present(self) -> bool:
"""Flag to check if workload is present and ready."""
pass
def write_text(
self,
content: str,
path: pathops.PathProtocol,
mode: int | None = None,
user: str | None = None,
group: str | None = None,
) -> None:
"""Write content to a file on disk.
Args:
content (str): The content to be written.
path (pathops.PathProtocol): The file path where the content should be written.
mode (int, optional): The mode/permissions to use when writing the file.
user (str, optional): The user to own the file (forwarded to pathops for
substrate-correct chown: os.chown on VM, Pebble push on K8s).
group (str, optional): The group to own the file (forwarded to pathops).
Raises:
PostgreSQLFileOperationError: If there is an error during the file write operation.
"""
try:
path.write_text(content, mode=mode, user=user, group=group)
except (
FileNotFoundError,
LookupError,
NotADirectoryError,
PermissionError,
pathops.PebbleConnectionError,
PebbleError,
ValueError,
) as e:
raise PostgreSQLFileOperationError(e) from e
def read_text(self, path: pathops.PathProtocol) -> str:
"""Read content from a file on disk.
Args:
path (pathops.PathProtocol): The file path to read from.
Returns:
str: The content read from the file.
"""
try:
return path.read_text()
except (
FileNotFoundError,
UnicodeError,
PermissionError,
PebbleError,
ModelError,
pathops.PebbleConnectionError,
) as e:
raise PostgreSQLFileOperationError(e) from e
def mkdir(
self,
path: pathops.PathProtocol,
mode: int = DIR_PERMISSIONS_READONLY,
parents: bool = False,
exist_ok: bool = False,
) -> None:
"""Create a directory on disk.
Args:
path (pathops.PathProtocol): The directory path to create.
mode (int): The mode/permissions to use for the new directory.
parents (bool): Whether to create parent directories if they do not exist.
exist_ok (bool): Whether to ignore the error if the directory already exists.
"""
try:
path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
except (
PebbleError,
ModelError,
FileExistsError,
FileNotFoundError,
LookupError,
NotADirectoryError,
PermissionError,
pathops.PebbleConnectionError,
ValueError,
) as e:
raise PostgreSQLFileOperationError(e) from e
def exists(self, path: pathops.PathProtocol) -> bool:
"""Check if a file or directory exists on disk.
Args:
path (pathops.PathProtocol): The file or directory path to check.
Returns:
bool: True if the file or directory exists, False otherwise.
Raises:
PostgreSQLFileOperationError: If there is an error accessing the file system.
"""
try:
return path.exists()
except (PermissionError, pathops.PebbleConnectionError) as e:
raise PostgreSQLFileOperationError(e) from e
def unlink(self, path: pathops.PathProtocol, missing_ok: bool = False) -> None:
"""Remove a file from disk.
Args:
path (pathops.PathProtocol): The file path to remove.
missing_ok (bool): Whether to ignore the error if the file does not exist.
"""
try:
path.unlink(missing_ok=missing_ok)
except (
FileNotFoundError,
IsADirectoryError,
PermissionError,
pathops.PebbleConnectionError,
) as e:
raise PostgreSQLFileOperationError(e) from e
@contextmanager
@abstractmethod
def temp_file(
self,
mode: str = "w+b",
data: str | None = None,
encoding: str | None = None,
directory: PathProtocol | None = None,
delete: bool = True,
chown: str | None = None,
*,
errors: str | None = None,
suffix: str | None = None,
) -> Generator[PathProtocol, None, None]:
"""Context manager for creating temporary files."""
raise NotImplementedError
@abstractmethod
def is_service_started(self, paused: bool | None = False) -> bool:
"""Check if the snap service is running.
Set paused=True if the process was intentionally paused.
"""
pass
@abstractmethod
def is_patroni_running(self) -> bool:
"""Check if the Patroni service is running."""
pass
@abstractmethod
def start_service_only(self):
"""Start the actual service only (snap / pebble)."""
pass
@abstractmethod
def run_cmd(
self,
command: str,
args: str | None = None,
use_errors_replace: bool = False,
stdin: str | None = None,
) -> SimpleNamespace:
"""Run Command in CLI."""
pass
@abstractmethod
def is_failed(self) -> bool:
"""Check if snap service failed."""
pass
@abstractmethod
def stop(self) -> None:
"""Stop the PostgreSQL service."""
pass
@abstractmethod
def start_service(self):
"""Start the PostgreSQL service."""
pass
@abstractmethod
def get_workload_version(self) -> str:
"""Get the workload version."""
raise NotImplementedError
def get_postgresql_version(self) -> str:
"""Return the PostgreSQL version from the system."""
with pathlib.Path("refresh_versions.toml").open("rb") as file:
return tomli.load(file)["workload"]
@abstractmethod
def get_available_memory(self) -> int:
"""Returns the system available memory in bytes."""
pass
@abstractmethod
def get_available_resources(self) -> tuple[int, int]:
"""Returns the available (cpu_cores, memory_bytes) for the workload."""
pass