Repository navigation
Expand file tree
/
Copy pathmanager.py
More file actions
365 lines (323 loc) · 12.3 KB
/
Copy pathmanager.py
File metadata and controls
365 lines (323 loc) · 12.3 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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
from __future__ import annotations
import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path
import yaml
from loguru import logger
from .. import constants as root_cs
from ..config import settings
from . import constants as cs
from .health import wait_for_memgraph, wait_for_qdrant
def _publishes_on_all_interfaces(mapping: object) -> bool:
"""Whether one `ports` entry publishes without a host address.
Long-form entries carry an explicit `host_ip`; short-form ones are
`[host_ip:]host:container`, so a host address is present exactly when the
mapping has two separators. A mapping bound to 0.0.0.0 or :: is public
even though it names a host.
"""
if isinstance(mapping, dict):
# YAML parses `host_ip: null` (or a bare `host_ip:`) as None, which
# Compose treats exactly like an omitted host: publish everywhere.
declared = [
"" if value is None else str(value).strip()
for key, value in mapping.items()
if key == "host_ip"
]
return not declared or declared[0] in ("", "0.0.0.0", "::")
if not isinstance(mapping, str):
return False
text = mapping.strip()
if text.count(":") < 2:
return True
host_ip = text.rsplit(":", 2)[0]
# Compose wraps an IPv6 host in brackets so its colons are not read as
# field separators, so `[::]` is the IPv6 wildcard and has to be unwrapped
# before it can be recognised as one.
if host_ip.startswith("[") and host_ip.endswith("]"):
host_ip = host_ip[1:-1]
return host_ip in ("0.0.0.0", "::", "*")
class StackError(RuntimeError):
pass
@dataclass
class StackStatus:
state: cs.StackState
memgraph_reachable: bool
qdrant_reachable: bool
compose_file: Path
memgraph_endpoint: str
qdrant_endpoint: str
class StackManager:
def __init__(
self,
home: Path | None = None,
package_compose: Path | None = None,
memgraph_host: str | None = None,
memgraph_port: int | None = None,
qdrant_port: int = 6333,
project_name: str = cs.COMPOSE_PROJECT_NAME,
) -> None:
self.home = (home or settings.CGR_HOME).expanduser()
self.package_compose = (
package_compose
or (Path(__file__).resolve().parent / cs.PACKAGE_COMPOSE_RELATIVE).resolve()
)
self.memgraph_host = memgraph_host or settings.MEMGRAPH_HOST
self.memgraph_port = memgraph_port or settings.MEMGRAPH_PORT
self.qdrant_port = qdrant_port
self.project_name = project_name
@property
def compose_file(self) -> Path:
return self.home / cs.COMPOSE_FILENAME
def ensure_home(self) -> None:
self.home.mkdir(parents=True, exist_ok=True)
def ensure_compose_file(self) -> Path:
self.ensure_home()
target = self.compose_file
if not target.exists():
if not self.package_compose.exists():
raise StackError(
cs.ERR_COMPOSE_FILE_MISSING.format(path=self.package_compose)
)
logger.info(cs.MSG_RENDERING_COMPOSE.format(path=target))
shutil.copyfile(self.package_compose, target)
else:
self._warn_if_ports_are_public(target)
return target
@staticmethod
def _public_port_mappings(compose_file: Path) -> list[str]:
"""Published ports a compose file leaves bound to every interface.
Decided from the parsed `services.*.ports` entries, not from whether
some token appears in the text: a mapping is public exactly when it
carries no host address, so one corrected service, or the bind-host
name sitting in a comment, cannot vouch for the rest of the file
(issue #1012).
"""
try:
compose = yaml.safe_load(compose_file.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, yaml.YAMLError):
return []
if not isinstance(compose, dict):
return []
services = compose.get("services")
if not isinstance(services, dict):
return []
public: list[str] = []
for service, spec in services.items():
if not isinstance(spec, dict):
continue
# The file is user-owned, so `ports` can be any YAML value; a
# scalar (`ports: 8080`) is not a mapping list and iterating it
# would crash the start and status paths over a file Compose
# itself would reject.
ports = spec.get("ports")
if not isinstance(ports, list):
continue
for mapping in ports:
if _publishes_on_all_interfaces(mapping):
public.append(f"{service}: {mapping}")
return public
@classmethod
def _warn_if_ports_are_public(cls, compose_file: Path) -> None:
"""Flag a compose file that still publishes on every interface.
The file is rendered once and never overwritten, so an existing install
keeps publishing the unauthenticated Memgraph and Qdrant endpoints on
every interface. It is the user's file and may carry their edits, so
this reports the exposure and names the remedy rather than clobbering
it.
"""
public = cls._public_port_mappings(compose_file)
if not public:
return
logger.warning(
cs.WARN_COMPOSE_PORTS_PUBLIC.format(
path=compose_file, mappings=", ".join(public)
)
)
def warn_if_ports_are_public(self) -> None:
"""Warn about public port bindings independently of the start path.
`ensure_compose_file` only runs when the stack is being started, so a
stack that is already up would keep its pre-#1012 exposure silent
(issue #1380). Callers that never render the file go through here.
"""
if self.compose_file.exists():
self._warn_if_ports_are_public(self.compose_file)
def check_docker(self) -> None:
if shutil.which(cs.DOCKER_BIN) is None:
raise StackError(cs.ERR_DOCKER_NOT_INSTALLED)
info = subprocess.run(
[cs.DOCKER_BIN, "info"],
capture_output=True,
text=True,
encoding=root_cs.ENCODING_UTF8,
timeout=cs.DEFAULT_STATUS_TIMEOUT_S,
check=False,
)
if info.returncode != 0:
raise StackError(cs.ERR_DOCKER_DAEMON_DOWN)
compose = subprocess.run(
[cs.DOCKER_BIN, cs.DOCKER_COMPOSE_SUBCOMMAND, "version"],
capture_output=True,
text=True,
encoding=root_cs.ENCODING_UTF8,
timeout=cs.DEFAULT_STATUS_TIMEOUT_S,
check=False,
)
if compose.returncode != 0:
raise StackError(cs.ERR_COMPOSE_NOT_AVAILABLE)
def _compose_cmd(self, *args: str) -> list[str]:
return [
cs.DOCKER_BIN,
cs.DOCKER_COMPOSE_SUBCOMMAND,
"-p",
self.project_name,
"-f",
str(self.compose_file),
*args,
]
def up(self, timeout: float = cs.DEFAULT_DOCKER_TIMEOUT_S) -> None:
self.check_docker()
self.ensure_compose_file()
logger.info(cs.MSG_STARTING_STACK)
result = subprocess.run(
self._compose_cmd("up", "-d"),
capture_output=True,
text=True,
encoding=root_cs.ENCODING_UTF8,
timeout=timeout,
check=False,
)
if result.returncode != 0:
raise StackError(
cs.ERR_STACK_START_FAILED.format(
detail=result.stderr.strip() or result.stdout.strip()
)
)
def down(self, timeout: float = cs.DEFAULT_DOCKER_TIMEOUT_S) -> None:
if not self.compose_file.exists():
return
if shutil.which(cs.DOCKER_BIN) is None:
raise StackError(cs.ERR_DOCKER_NOT_INSTALLED)
logger.info(cs.MSG_STOPPING_STACK)
result = subprocess.run(
self._compose_cmd("down"),
capture_output=True,
text=True,
encoding=root_cs.ENCODING_UTF8,
timeout=timeout,
check=False,
)
if result.returncode != 0:
raise StackError(
cs.ERR_STACK_STOP_FAILED.format(
detail=result.stderr.strip() or result.stdout.strip()
)
)
def logs(
self,
service: str | None = None,
follow: bool = False,
tail: int | None = 200,
) -> int:
if not self.compose_file.exists():
raise StackError(cs.ERR_COMPOSE_FILE_MISSING.format(path=self.compose_file))
args: list[str] = ["logs"]
if follow:
args.append("-f")
if tail is not None:
args.extend(["--tail", str(tail)])
if service:
args.append(service)
completed = subprocess.run(self._compose_cmd(*args), check=False)
return completed.returncode
def restart(self) -> None:
logger.info(cs.MSG_RESTARTING_STACK)
self.down()
self.up()
def wait_healthy(
self,
timeout: float = cs.DEFAULT_HEALTH_TIMEOUT_S,
) -> None:
logger.info(
cs.MSG_WAITING_FOR_HEALTH.format(
service=cs.SERVICE_MEMGRAPH,
host=self.memgraph_host,
port=self.memgraph_port,
)
)
if not wait_for_memgraph(self.memgraph_host, self.memgraph_port, timeout):
raise StackError(
cs.ERR_STACK_NOT_HEALTHY.format(
service=cs.SERVICE_MEMGRAPH, timeout=timeout
)
)
logger.info(
cs.MSG_WAITING_FOR_HEALTH.format(
service=cs.SERVICE_QDRANT,
host=cs.LOOPBACK_HOST,
port=self.qdrant_port,
)
)
if not wait_for_qdrant(self.qdrant_port, timeout):
raise StackError(
cs.ERR_STACK_NOT_HEALTHY.format(
service=cs.SERVICE_QDRANT, timeout=timeout
)
)
def status(self) -> StackStatus:
memgraph_ok = wait_for_memgraph(
self.memgraph_host, self.memgraph_port, timeout=0.1, interval=0.0
)
qdrant_ok = wait_for_qdrant(self.qdrant_port, timeout=0.1, interval=0.0)
match (memgraph_ok, qdrant_ok):
case (True, True):
state = cs.StackState.RUNNING
case (False, False):
state = cs.StackState.STOPPED
case _:
state = cs.StackState.PARTIAL
return StackStatus(
state=state,
memgraph_reachable=memgraph_ok,
qdrant_reachable=qdrant_ok,
compose_file=self.compose_file,
memgraph_endpoint=f"{self.memgraph_host}:{self.memgraph_port}",
qdrant_endpoint=f"{cs.LOOPBACK_HOST}:{self.qdrant_port}",
)
def ensure_running(self) -> StackStatus:
current = self.status()
if current.state == cs.StackState.RUNNING:
logger.info(cs.MSG_STACK_ALREADY_RUNNING)
# The start path warns via ensure_compose_file; a stack that is
# already up never reaches it, and its long-lived compose file is
# exactly the profile of a pre-#1012 public binding (issue #1380).
self.warn_if_ports_are_public()
return current
self.up()
self.wait_healthy()
final = self.status()
logger.info(
cs.MSG_STACK_HEALTHY.format(
memgraph=final.memgraph_endpoint,
qdrant=final.qdrant_endpoint,
)
)
return final
def ensure_running() -> StackStatus:
return StackManager().ensure_running()
def daemon_up() -> StackStatus:
mgr = StackManager()
mgr.up()
mgr.wait_healthy()
return mgr.status()
def daemon_down() -> None:
StackManager().down()
def daemon_status() -> StackStatus:
return StackManager().status()
def daemon_logs(service: str | None = None, follow: bool = False) -> int:
return StackManager().logs(service=service, follow=follow)
def daemon_restart() -> StackStatus:
mgr = StackManager()
mgr.restart()
mgr.wait_healthy()
return mgr.status()