qodalis-cli-server-plugin-docker 1.0.0b39__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.
- qodalis_cli_docker/__init__.py +44 -0
- qodalis_cli_docker/builder.py +196 -0
- qodalis_cli_docker/commands.py +1434 -0
- qodalis_cli_docker/compose.py +319 -0
- qodalis_cli_docker/console/extension.css +32 -0
- qodalis_cli_docker/console/extension.js +89 -0
- qodalis_cli_docker/console_page.py +28 -0
- qodalis_cli_docker/controller.py +309 -0
- qodalis_cli_docker/engine.py +482 -0
- qodalis_cli_docker/exec_socket.py +246 -0
- qodalis_cli_docker/mcp_tools.py +149 -0
- qodalis_cli_docker/plugin.py +36 -0
- qodalis_cli_docker/service.py +2007 -0
- qodalis_cli_docker/settings.py +172 -0
- qodalis_cli_docker/shapes.py +317 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/METADATA +300 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/RECORD +20 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/WHEEL +4 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/entry_points.txt +2 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,1434 @@
|
|
|
1
|
+
"""The ``docker`` terminal commands, output v2 (typed tables with status tones, key-value panels, progress; errors are one
|
|
2
|
+
``Error: <text>`` line, exit 1). They call the same service as the routes, so hide, protect and read-only hold for them
|
|
3
|
+
too. The output of each is the one of the Node plugin (``docs/output-v2-commands.md`` there)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from typing import Any, Optional, Sequence
|
|
14
|
+
|
|
15
|
+
from qodalis_cli_server_abstractions import (
|
|
16
|
+
CliCommandExample,
|
|
17
|
+
CliCommandParameterDescriptor,
|
|
18
|
+
CliCommandProcessor,
|
|
19
|
+
CliModule,
|
|
20
|
+
CliOutput,
|
|
21
|
+
CliPromptUnavailableError,
|
|
22
|
+
CliProcessCommand,
|
|
23
|
+
CliSessionUnavailableError,
|
|
24
|
+
ICliCommandProcessor,
|
|
25
|
+
col,
|
|
26
|
+
get_positionals,
|
|
27
|
+
quote_shell_word,
|
|
28
|
+
split_shell_words,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from .controller import DOCKER_ADMIN, DOCKER_EXEC, DOCKER_MANAGE, DOCKER_READ
|
|
32
|
+
from .engine import DockerError
|
|
33
|
+
from .exec_socket import EXEC_SOCKET_PATH
|
|
34
|
+
from .service import CONTAINER_ACTIONS, DockerCaller, DockerService
|
|
35
|
+
from .shapes import parse_time
|
|
36
|
+
|
|
37
|
+
_HOST = CliCommandParameterDescriptor("host", "The Docker host (default: local)", False, "string")
|
|
38
|
+
_JSON = CliCommandParameterDescriptor("json", "Print the result as JSON", False, "boolean")
|
|
39
|
+
_YES = CliCommandParameterDescriptor("yes", "Do not ask for confirmation", False, "boolean", aliases=["y"])
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _force(text: str) -> CliCommandParameterDescriptor:
|
|
43
|
+
return CliCommandParameterDescriptor("force", text, False, "boolean")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
CONTAINER_STATE_TONES = {"running": "success", "paused": "warning", "restarting": "warning", "removing": "warning", "created": "muted", "exited": "muted", "dead": "error"}
|
|
47
|
+
HEALTH_TONES = {"healthy": "success", "unhealthy": "error", "starting": "warning"}
|
|
48
|
+
STACK_STATE_TONES = {"running": "success", "partial": "warning", "stopped": "muted", "down": "muted"}
|
|
49
|
+
HOST_STATE_TONES = {"reachable": "success", "unreachable": "error"}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _host_of(command: CliProcessCommand) -> Optional[str]:
|
|
53
|
+
h = (command.args or {}).get("host")
|
|
54
|
+
return h if isinstance(h, str) and h else None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _flag(command: CliProcessCommand, name: str, alias: Optional[str] = None) -> bool:
|
|
58
|
+
for key in (name, alias):
|
|
59
|
+
if not key:
|
|
60
|
+
continue
|
|
61
|
+
v = (command.args or {}).get(key)
|
|
62
|
+
if v is True or v == "true":
|
|
63
|
+
return True
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _str_arg(command: CliProcessCommand, *names: str) -> Optional[str]:
|
|
68
|
+
for name in names:
|
|
69
|
+
v = (command.args or {}).get(name)
|
|
70
|
+
if isinstance(v, str):
|
|
71
|
+
return v
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _caller() -> DockerCaller:
|
|
76
|
+
"""The user running the command (``get_cli_caller``), when the server provides it; ``signed_in`` feeds the sign-in rule."""
|
|
77
|
+
try:
|
|
78
|
+
from qodalis_cli import get_cli_caller # the server package, optional here
|
|
79
|
+
except ImportError:
|
|
80
|
+
return DockerCaller()
|
|
81
|
+
caller = get_cli_caller()
|
|
82
|
+
name = getattr(caller, "user_name", None) if caller is not None else None
|
|
83
|
+
admin = False # no principal: the service decides (allowUnprotected)
|
|
84
|
+
if caller is not None:
|
|
85
|
+
can = getattr(caller, "can", None)
|
|
86
|
+
admin = bool(can(DOCKER_ADMIN)) if callable(can) else False
|
|
87
|
+
return DockerCaller(name=name or None, signed_in=caller is not None, admin=admin)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _fail(out: CliOutput, err: Any) -> int:
|
|
91
|
+
"""``Error: <message>`` (error style); exit code 1."""
|
|
92
|
+
text = err.message if isinstance(err, DockerError) else str(err)
|
|
93
|
+
out.error(text if text.startswith("Error: ") else f"Error: {text}")
|
|
94
|
+
return 1
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
async def _guarded(out: CliOutput, body: Any) -> int:
|
|
98
|
+
"""Runs a command body, turning any error into the ``Error:`` line."""
|
|
99
|
+
try:
|
|
100
|
+
code = await body()
|
|
101
|
+
return 0 if code is None else code
|
|
102
|
+
except (CliPromptUnavailableError, CliSessionUnavailableError):
|
|
103
|
+
# the framework writes the one error of a prompt or a session nobody can answer
|
|
104
|
+
raise
|
|
105
|
+
except Exception as err: # noqa: BLE001
|
|
106
|
+
return _fail(out, err)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _print_json(out: CliOutput, payload: Any) -> int:
|
|
110
|
+
out.text(json.dumps(payload, indent=2, ensure_ascii=False))
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def format_bytes(value: float) -> str:
|
|
115
|
+
"""1536 -> ``1.5 KB``."""
|
|
116
|
+
units = ["B", "KB", "MB", "GB", "TB"]
|
|
117
|
+
unit = 0
|
|
118
|
+
while value >= 1024 and unit < len(units) - 1:
|
|
119
|
+
value /= 1024
|
|
120
|
+
unit += 1
|
|
121
|
+
if unit == 0:
|
|
122
|
+
shown = str(int(value)) if float(value).is_integer() else str(value)
|
|
123
|
+
else:
|
|
124
|
+
shown = f"{value:.{1 if value < 10 else 0}f}"
|
|
125
|
+
return f"{shown} {units[unit]}"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def ports_text(container: dict[str, Any]) -> str:
|
|
129
|
+
"""``8080->80/tcp, 5432/tcp``: the ports of a container, the IPv4 and IPv6 binding of one port shown once."""
|
|
130
|
+
seen: list[str] = []
|
|
131
|
+
for p in container["ports"]:
|
|
132
|
+
text = f"{p['public']}->{p['private']}/{p['type']}" if p.get("public") else f"{p['private']}/{p['type']}"
|
|
133
|
+
if text not in seen:
|
|
134
|
+
seen.append(text)
|
|
135
|
+
return ", ".join(seen)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _duration_seconds(text: str) -> Optional[int]:
|
|
139
|
+
m = re.match(r"^(\d+)([smhd])$", text.strip())
|
|
140
|
+
if not m:
|
|
141
|
+
return None
|
|
142
|
+
return int(m.group(1)) * {"s": 1, "m": 60, "h": 3600, "d": 86400}[m.group(2)]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _iso_ms(seconds: float) -> str:
|
|
146
|
+
moment = datetime.fromtimestamp(math.floor(seconds * 1000) / 1000, tz=timezone.utc)
|
|
147
|
+
return moment.strftime("%Y-%m-%dT%H:%M:%S.") + f"{moment.microsecond // 1000:03d}Z"
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _since_of(command: CliProcessCommand, now: datetime) -> dict[str, Any] | str:
|
|
151
|
+
"""``--since``: a duration (``10m``) before now or an ISO time; an ``Error:`` text when invalid."""
|
|
152
|
+
raw = (command.args or {}).get("since")
|
|
153
|
+
if raw is None:
|
|
154
|
+
return {}
|
|
155
|
+
text = str(raw)
|
|
156
|
+
if raw is True or not text:
|
|
157
|
+
return "Error: --since needs a value"
|
|
158
|
+
seconds = _duration_seconds(text)
|
|
159
|
+
if seconds is not None:
|
|
160
|
+
return {"seconds": seconds, "iso": _iso_ms(now.timestamp() - seconds)}
|
|
161
|
+
parsed = parse_time(text)
|
|
162
|
+
if parsed is None:
|
|
163
|
+
return "Error: --since must be a duration (30s, 10m, 2h, 1d) or an ISO 8601 time"
|
|
164
|
+
return {"iso": _iso_ms(parsed), "seconds": max(1, math.floor((now.timestamp() - parsed) + 0.5))}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _whole_arg(command: CliProcessCommand, name: str, low: int, high: int) -> int | None | str:
|
|
168
|
+
raw = (command.args or {}).get(name)
|
|
169
|
+
if raw is None or raw is True:
|
|
170
|
+
return None
|
|
171
|
+
try:
|
|
172
|
+
n = float(raw) if not isinstance(raw, bool) else float("nan")
|
|
173
|
+
except (TypeError, ValueError):
|
|
174
|
+
n = float("nan")
|
|
175
|
+
if n != n or not n.is_integer() or n < low or n > high:
|
|
176
|
+
return f"Error: --{name} must be a whole number from {low} to {high}"
|
|
177
|
+
return int(n)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _names(items: Sequence[str]) -> str:
|
|
181
|
+
return ", ".join(items)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
async def _confirmed(command: CliProcessCommand, out: CliOutput, question: str) -> bool:
|
|
185
|
+
"""Asks ``question`` (flag ``yes``, ``-y``); false when declined."""
|
|
186
|
+
if _flag(command, "y"):
|
|
187
|
+
return True
|
|
188
|
+
return await out.confirm(question, flag="yes")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _write_containers(out: CliOutput, containers: list[dict[str, Any]], with_stack: bool) -> None:
|
|
192
|
+
columns = [col.text("Name"), col.text("Image"), col.status("State", CONTAINER_STATE_TONES), col.text("Status"), col.status("Health", HEALTH_TONES), col.text("Ports")]
|
|
193
|
+
if with_stack:
|
|
194
|
+
columns.append(col.text("Stack"))
|
|
195
|
+
out.table(
|
|
196
|
+
[[c["name"], c["image"], c["state"], c["status"], c["health"] or "", ports_text(c), *([c["stack"] or ""] if with_stack else [])] for c in containers],
|
|
197
|
+
columns,
|
|
198
|
+
row_command=[f"docker inspect {c['name']}" for c in containers],
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
async def _follow_operation(service: DockerService, start: dict[str, Any], out: CliOutput, running: str, done: str, failed: str) -> int:
|
|
203
|
+
"""Follows an operation (pull): one progress block whose label shows the bytes; the final label says the result."""
|
|
204
|
+
progress = out.progress(running)
|
|
205
|
+
last = ""
|
|
206
|
+
waiter = asyncio.ensure_future(service.wait_operation(start["id"]))
|
|
207
|
+
try:
|
|
208
|
+
while True:
|
|
209
|
+
await asyncio.wait({waiter}, timeout=0.15)
|
|
210
|
+
if waiter.done():
|
|
211
|
+
break
|
|
212
|
+
try:
|
|
213
|
+
op = service.operation(start["id"], _caller())["operation"]
|
|
214
|
+
except DockerError:
|
|
215
|
+
continue
|
|
216
|
+
if op.get("progress") and op["kind"] == "pull":
|
|
217
|
+
label = f"{running}: {format_bytes(op['progress']['current'])} / {format_bytes(op['progress']['total'])}"
|
|
218
|
+
elif op.get("message"):
|
|
219
|
+
label = f"{running}: {op['message']}"
|
|
220
|
+
else:
|
|
221
|
+
label = running
|
|
222
|
+
if label != last:
|
|
223
|
+
last = label
|
|
224
|
+
progress.update(0, label)
|
|
225
|
+
final = waiter.result()
|
|
226
|
+
finally:
|
|
227
|
+
if not waiter.done():
|
|
228
|
+
waiter.cancel()
|
|
229
|
+
if final["state"] == "failed":
|
|
230
|
+
progress.fail(failed)
|
|
231
|
+
out.error(f"Error: {final.get('error')}")
|
|
232
|
+
return 1
|
|
233
|
+
progress.done(done)
|
|
234
|
+
return 0
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class _DockerProcessor(CliCommandProcessor):
|
|
238
|
+
# plain attributes (not the base class's properties) so a processor can set them per instance
|
|
239
|
+
command = ""
|
|
240
|
+
description = ""
|
|
241
|
+
aliases: Any = None
|
|
242
|
+
examples: Any = None
|
|
243
|
+
processors: Any = None
|
|
244
|
+
parameters = [_HOST]
|
|
245
|
+
required_permissions: list[str] | None = None # type: ignore[assignment]
|
|
246
|
+
|
|
247
|
+
def __init__(self, service: DockerService) -> None:
|
|
248
|
+
self.service = service
|
|
249
|
+
|
|
250
|
+
async def _guarded(self, out: CliOutput, body: Any) -> int:
|
|
251
|
+
""":func:`_guarded`, after the sign-in rule (the Docker plugin needs a protected server unless ``allowUnprotected`` is on)."""
|
|
252
|
+
|
|
253
|
+
async def checked() -> Any:
|
|
254
|
+
self.service.assert_caller(_caller())
|
|
255
|
+
return await body()
|
|
256
|
+
|
|
257
|
+
return await _guarded(out, checked)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _write_sub_commands(out: CliOutput, path: str, description: str, processors: Sequence[ICliCommandProcessor]) -> None:
|
|
261
|
+
"""``docker <group>`` run alone: a heading and the sub-commands."""
|
|
262
|
+
out.heading(description, icon="server")
|
|
263
|
+
out.table(
|
|
264
|
+
[[p.command, p.description or ""] for p in processors],
|
|
265
|
+
[col.code("Command"), col.text("Description")],
|
|
266
|
+
row_command=[None if p.value_required else f"{path} {p.command}" for p in processors],
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _write_hosts(out: CliOutput, hosts: list[dict[str, Any]]) -> None:
|
|
271
|
+
out.table(
|
|
272
|
+
[[h["name"], h["endpoint"], "reachable" if h["reachable"] else "unreachable", h.get("version") or "", h.get("containers")] for h in hosts],
|
|
273
|
+
[col.text("Name"), col.text("Endpoint"), col.status("State", HOST_STATE_TONES), col.text("Version"), col.number("Containers")],
|
|
274
|
+
)
|
|
275
|
+
for h in hosts:
|
|
276
|
+
if not h["reachable"] and h.get("error"):
|
|
277
|
+
out.warning(f"{h['name']}: {h['error']}")
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# -- hosts, ps, inspect, logs, stats ------------------------------------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
class _HostsProcessor(_DockerProcessor):
|
|
284
|
+
command = "hosts"
|
|
285
|
+
description = "Lists the Docker hosts and whether they answer"
|
|
286
|
+
parameters = [_JSON]
|
|
287
|
+
|
|
288
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
289
|
+
async def body() -> Optional[int]:
|
|
290
|
+
result = await self.service.hosts()
|
|
291
|
+
if _flag(command, "json"):
|
|
292
|
+
return _print_json(out, result)
|
|
293
|
+
_write_hosts(out, result["hosts"])
|
|
294
|
+
return None
|
|
295
|
+
|
|
296
|
+
return await self._guarded(out, body)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class _PsProcessor(_DockerProcessor):
|
|
300
|
+
command = "ps"
|
|
301
|
+
description = "Lists containers (the running ones; --all for every one)"
|
|
302
|
+
aliases = ["ls"]
|
|
303
|
+
examples = [CliCommandExample("docker ps --all --stack shop", "Every container of the stack shop")]
|
|
304
|
+
parameters = [_HOST, CliCommandParameterDescriptor("all", "Include stopped containers", False, "boolean", aliases=["a"]),
|
|
305
|
+
CliCommandParameterDescriptor("stack", "Only this compose stack", False, "string"), _JSON]
|
|
306
|
+
|
|
307
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
308
|
+
async def body() -> Optional[int]:
|
|
309
|
+
stack = command.args.get("stack") if isinstance(command.args.get("stack"), str) else None
|
|
310
|
+
result = await self.service.list_containers(_host_of(command), all=_flag(command, "all", "a"), stack=stack)
|
|
311
|
+
if _flag(command, "json"):
|
|
312
|
+
return _print_json(out, result)
|
|
313
|
+
if not result["containers"]:
|
|
314
|
+
out.info("No containers.")
|
|
315
|
+
return None
|
|
316
|
+
_write_containers(out, result["containers"], True)
|
|
317
|
+
return None
|
|
318
|
+
|
|
319
|
+
return await self._guarded(out, body)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
class _InspectProcessor(_DockerProcessor):
|
|
323
|
+
command = "inspect"
|
|
324
|
+
description = "Shows a container in detail"
|
|
325
|
+
value_required = True
|
|
326
|
+
parameters = [_HOST, _JSON]
|
|
327
|
+
|
|
328
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
329
|
+
async def body() -> Optional[int]:
|
|
330
|
+
refs = get_positionals(command)
|
|
331
|
+
if not refs:
|
|
332
|
+
return _fail(out, "name a container: docker inspect <container>")
|
|
333
|
+
result = await self.service.get_container(_host_of(command), refs[0])
|
|
334
|
+
if _flag(command, "json"):
|
|
335
|
+
return _print_json(out, result)
|
|
336
|
+
c = result["container"]
|
|
337
|
+
out.panel("Container", lambda p: p.key_value([
|
|
338
|
+
{"key": "Name", "value": c["name"]},
|
|
339
|
+
{"key": "ID", "value": c["shortId"]},
|
|
340
|
+
{"key": "Image", "value": c["image"]},
|
|
341
|
+
{"key": "State", "value": c["state"], "type": "status", "tones": CONTAINER_STATE_TONES},
|
|
342
|
+
{"key": "Status", "value": c["status"]},
|
|
343
|
+
{"key": "Health", "value": c["health"] or "", "type": "status", "tones": HEALTH_TONES},
|
|
344
|
+
{"key": "Created", "value": c["createdAt"], "type": "datetime"},
|
|
345
|
+
{"key": "Started", "value": c["startedAt"], "type": "datetime"},
|
|
346
|
+
{"key": "Finished", "value": c["finishedAt"], "type": "datetime"},
|
|
347
|
+
{"key": "Exit code", "value": c["exitCode"], "type": "number"},
|
|
348
|
+
{"key": "Restart policy", "value": c["restartPolicy"]},
|
|
349
|
+
{"key": "Restarts", "value": c["restartCount"], "type": "number"},
|
|
350
|
+
{"key": "Command", "value": " ".join(c["command"])},
|
|
351
|
+
{"key": "Stack", "value": c["stack"] or ""},
|
|
352
|
+
{"key": "Service", "value": c["service"] or ""},
|
|
353
|
+
{"key": "Platform", "value": c["platform"]},
|
|
354
|
+
{"key": "Protected", "value": c["protected"], "type": "bool"},
|
|
355
|
+
]))
|
|
356
|
+
|
|
357
|
+
def ports(p: CliOutput) -> None:
|
|
358
|
+
if not c["ports"]:
|
|
359
|
+
p.info("No ports.")
|
|
360
|
+
else:
|
|
361
|
+
p.table([[x.get("ip", ""), x.get("public"), x["private"], x["type"]] for x in c["ports"]],
|
|
362
|
+
[col.text("IP"), col.number("Public"), col.number("Private"), col.text("Type")])
|
|
363
|
+
|
|
364
|
+
def mounts(p: CliOutput) -> None:
|
|
365
|
+
if not c["mounts"]:
|
|
366
|
+
p.info("No mounts.")
|
|
367
|
+
else:
|
|
368
|
+
p.table([[m["type"], m["source"], m["destination"], m["rw"]] for m in c["mounts"]],
|
|
369
|
+
[col.text("Type"), col.text("Source"), col.text("Destination"), col.bool("Writable")])
|
|
370
|
+
|
|
371
|
+
def networks(p: CliOutput) -> None:
|
|
372
|
+
if not c["networks"]:
|
|
373
|
+
p.info("No networks.")
|
|
374
|
+
else:
|
|
375
|
+
p.table([[n["name"], n["ip"], n["gateway"], n["mac"]] for n in c["networks"]],
|
|
376
|
+
[col.text("Name"), col.text("IP"), col.text("Gateway"), col.text("MAC")])
|
|
377
|
+
|
|
378
|
+
def environment(p: CliOutput) -> None:
|
|
379
|
+
if not c["env"]:
|
|
380
|
+
p.info("No environment.")
|
|
381
|
+
else:
|
|
382
|
+
p.key_value([
|
|
383
|
+
{"key": e[:e.index("=")] if "=" in e else e, "value": e[e.index("=") + 1:] if "=" in e else ""} for e in c["env"]
|
|
384
|
+
])
|
|
385
|
+
|
|
386
|
+
out.panel("Ports", ports)
|
|
387
|
+
out.panel("Mounts", mounts)
|
|
388
|
+
out.panel("Networks", networks)
|
|
389
|
+
out.panel("Environment", environment)
|
|
390
|
+
return None
|
|
391
|
+
|
|
392
|
+
return await self._guarded(out, body)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
class _LogsProcessor(_DockerProcessor):
|
|
396
|
+
command = "logs"
|
|
397
|
+
description = "Shows the log of a container"
|
|
398
|
+
examples = [CliCommandExample("docker logs web --tail 50 --since 10m", "The last 50 lines of the last ten minutes")]
|
|
399
|
+
value_required = True
|
|
400
|
+
parameters = [
|
|
401
|
+
_HOST,
|
|
402
|
+
CliCommandParameterDescriptor("tail", "How many lines (1-2000, default 100)", False, "number", aliases=["n"], default_value=100),
|
|
403
|
+
CliCommandParameterDescriptor("since", "Only lines after this: 10m, 2h, 1d or an ISO 8601 time", False, "string"),
|
|
404
|
+
CliCommandParameterDescriptor("timestamps", "Show the time of each line", False, "boolean", aliases=["t"]),
|
|
405
|
+
CliCommandParameterDescriptor("follow", "Keep streaming new lines until stopped", False, "boolean", aliases=["f"]),
|
|
406
|
+
_JSON,
|
|
407
|
+
]
|
|
408
|
+
|
|
409
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
410
|
+
async def body() -> Optional[int]:
|
|
411
|
+
refs = get_positionals(command)
|
|
412
|
+
if not refs:
|
|
413
|
+
return _fail(out, "name a container: docker logs <container>")
|
|
414
|
+
ref = refs[0]
|
|
415
|
+
tail = _whole_arg(command, "tail", 1, 2000)
|
|
416
|
+
if tail is None:
|
|
417
|
+
tail = _whole_arg(command, "n", 1, 2000)
|
|
418
|
+
if isinstance(tail, str):
|
|
419
|
+
return _fail(out, tail)
|
|
420
|
+
since = _since_of(command, self.service.clock)
|
|
421
|
+
if isinstance(since, str):
|
|
422
|
+
return _fail(out, since)
|
|
423
|
+
timestamps = _flag(command, "timestamps", "t")
|
|
424
|
+
|
|
425
|
+
def write(lines: list[dict[str, Any]]) -> None:
|
|
426
|
+
group: list[str] = []
|
|
427
|
+
stream = ""
|
|
428
|
+
|
|
429
|
+
def flush() -> None:
|
|
430
|
+
nonlocal group
|
|
431
|
+
if group:
|
|
432
|
+
out.text("\n".join(group), "warning" if stream == "stderr" else None)
|
|
433
|
+
group = []
|
|
434
|
+
|
|
435
|
+
for line in lines:
|
|
436
|
+
if line["stream"] != stream:
|
|
437
|
+
flush()
|
|
438
|
+
stream = line["stream"]
|
|
439
|
+
group.append(f"{line['time']} {line['text']}" if timestamps and line.get("time") else line["text"])
|
|
440
|
+
flush()
|
|
441
|
+
|
|
442
|
+
if _flag(command, "follow", "f"):
|
|
443
|
+
if not out.interactive:
|
|
444
|
+
return _fail(out, "--follow needs a streaming terminal")
|
|
445
|
+
await self.service.follow_logs(_host_of(command), ref, write, tail=tail, since=since.get("iso"), timestamps=True)
|
|
446
|
+
return None
|
|
447
|
+
result = await self.service.logs(_host_of(command), ref, tail=tail, since=since.get("iso"), timestamps=True)
|
|
448
|
+
if _flag(command, "json"):
|
|
449
|
+
return _print_json(out, result)
|
|
450
|
+
if not result["lines"]:
|
|
451
|
+
out.info("No log lines.")
|
|
452
|
+
return None
|
|
453
|
+
write(result["lines"])
|
|
454
|
+
return None
|
|
455
|
+
|
|
456
|
+
return await self._guarded(out, body)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
class _StatsProcessor(_DockerProcessor):
|
|
460
|
+
command = "stats"
|
|
461
|
+
description = "Shows CPU, memory, network and block I/O of the running containers"
|
|
462
|
+
parameters = [_HOST, CliCommandParameterDescriptor("watch", "Refresh every 2 seconds until stopped", False, "boolean", aliases=["w"]), _JSON]
|
|
463
|
+
|
|
464
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
465
|
+
async def body() -> Optional[int]:
|
|
466
|
+
refs = get_positionals(command)
|
|
467
|
+
columns = [col.text("Name"), col.number("CPU (%)", "cpu"), col.bytes("Memory"), col.bytes("Limit"), col.number("Memory (%)", "memoryPercent"),
|
|
468
|
+
col.bytes("Net in"), col.bytes("Net out"), col.bytes("Block read"), col.bytes("Block write"), col.number("PIDs")]
|
|
469
|
+
|
|
470
|
+
def rows(stats: list[dict[str, Any]]) -> list[list[Any]]:
|
|
471
|
+
return [[s["name"], s["cpuPercent"], s["memoryBytes"], s["memoryLimitBytes"], s["memoryPercent"], s["netRxBytes"], s["netTxBytes"],
|
|
472
|
+
s["blockReadBytes"], s["blockWriteBytes"], s["pids"]] for s in stats]
|
|
473
|
+
|
|
474
|
+
async def once() -> dict[str, Any]:
|
|
475
|
+
return await self.service.stats(_host_of(command), refs or None)
|
|
476
|
+
|
|
477
|
+
first = await once()
|
|
478
|
+
if _flag(command, "json"):
|
|
479
|
+
return _print_json(out, first)
|
|
480
|
+
if not first["stats"]:
|
|
481
|
+
out.info("No running containers.")
|
|
482
|
+
return None
|
|
483
|
+
watch = _flag(command, "watch", "w")
|
|
484
|
+
out.table(rows(first["stats"]), columns, id="docker-stats" if watch else None)
|
|
485
|
+
if not watch:
|
|
486
|
+
return None
|
|
487
|
+
if not out.interactive:
|
|
488
|
+
return _fail(out, "--watch needs a streaming terminal")
|
|
489
|
+
while True:
|
|
490
|
+
await asyncio.sleep(2)
|
|
491
|
+
out.table(rows((await once())["stats"]), columns, id="docker-stats")
|
|
492
|
+
|
|
493
|
+
return await self._guarded(out, body)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
# -- container actions, rm, exec ----------------------------------------------------------------------------------------
|
|
497
|
+
|
|
498
|
+
_PAST = {"start": "started", "stop": "stopped", "restart": "restarted", "kill": "killed", "pause": "paused", "unpause": "unpaused"}
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
class _ActionProcessor(_DockerProcessor):
|
|
502
|
+
command = ""
|
|
503
|
+
description = ""
|
|
504
|
+
value_required = True
|
|
505
|
+
required_permissions = [DOCKER_MANAGE] # type: ignore[assignment]
|
|
506
|
+
|
|
507
|
+
def __init__(self, service: DockerService, action: str) -> None:
|
|
508
|
+
super().__init__(service)
|
|
509
|
+
self.action = action
|
|
510
|
+
self.command = action
|
|
511
|
+
self.description = f"{action[0].upper()}{action[1:]}s one or more containers"
|
|
512
|
+
self.examples = [CliCommandExample(f"docker {action} web db")]
|
|
513
|
+
|
|
514
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
515
|
+
async def body() -> Optional[int]:
|
|
516
|
+
refs = get_positionals(command)
|
|
517
|
+
if not refs:
|
|
518
|
+
return _fail(out, f"name a container: docker {self.action} <container...>")
|
|
519
|
+
code = 0
|
|
520
|
+
for ref in refs:
|
|
521
|
+
try:
|
|
522
|
+
result = await self.service.container_action(_host_of(command), ref, self.action, _caller())
|
|
523
|
+
out.success(f"{result['container']['name']}: {_PAST[self.action]}")
|
|
524
|
+
except Exception as err: # noqa: BLE001
|
|
525
|
+
code = 1
|
|
526
|
+
out.error(f"Error: {ref}: {err.message if isinstance(err, DockerError) else err}")
|
|
527
|
+
return code
|
|
528
|
+
|
|
529
|
+
return await self._guarded(out, body)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
class _RmProcessor(_DockerProcessor):
|
|
533
|
+
command = "rm"
|
|
534
|
+
description = "Removes one or more containers"
|
|
535
|
+
value_required = True
|
|
536
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
537
|
+
parameters = [_HOST, _force("Remove a running container (kill it first)"),
|
|
538
|
+
CliCommandParameterDescriptor("volumes", "Remove the anonymous volumes of the containers too", False, "boolean", aliases=["v"]), _YES]
|
|
539
|
+
|
|
540
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
541
|
+
async def body() -> Optional[int]:
|
|
542
|
+
refs = get_positionals(command)
|
|
543
|
+
if not refs:
|
|
544
|
+
return _fail(out, "name a container: docker rm <container...>")
|
|
545
|
+
self.service.assert_writable()
|
|
546
|
+
if not await _confirmed(command, out, f"Remove {'container' if len(refs) == 1 else 'containers'} {_names(refs)}?"):
|
|
547
|
+
out.info("Not removed.")
|
|
548
|
+
return None
|
|
549
|
+
code = 0
|
|
550
|
+
for ref in refs:
|
|
551
|
+
try:
|
|
552
|
+
await self.service.remove_container(_host_of(command), ref, force=_flag(command, "force"), volumes=_flag(command, "volumes", "v"), caller=_caller())
|
|
553
|
+
out.success(f"{ref}: removed")
|
|
554
|
+
except Exception as err: # noqa: BLE001
|
|
555
|
+
code = 1
|
|
556
|
+
out.error(f"Error: {ref}: {err.message if isinstance(err, DockerError) else err}")
|
|
557
|
+
return code
|
|
558
|
+
|
|
559
|
+
return await self._guarded(out, body)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
_INTERACTIVE_FLAGS = ["it", "ti", "interactive", "i", "tty", "t"]
|
|
563
|
+
#: Flags of ``docker exec`` that take a value.
|
|
564
|
+
_EXEC_VALUE_FLAGS = {"user", "u", "workdir", "w", "timeout", "host"}
|
|
565
|
+
_FLAG_WORD = re.compile(r"^--?([A-Za-z][\w-]*)(=.*)?$")
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
@dataclass
|
|
569
|
+
class _ExecInvocation:
|
|
570
|
+
"""What ``docker exec`` was typed with: its options (only those before the container), the container and the command words."""
|
|
571
|
+
|
|
572
|
+
interactive: bool = False
|
|
573
|
+
host: Optional[str] = None
|
|
574
|
+
user: Optional[str] = None
|
|
575
|
+
workdir: Optional[str] = None
|
|
576
|
+
timeout: Optional[str] = None
|
|
577
|
+
ref: Optional[str] = None
|
|
578
|
+
words: list[str] = field(default_factory=list)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def _parse_exec(command: CliProcessCommand) -> _ExecInvocation:
|
|
582
|
+
"""``docker exec [options] <container> [command...]``, as in the docker CLI: the options (``-i``, ``-t``, ``-it``,
|
|
583
|
+
``--interactive``, ``--tty``, ``--user``/``-u``, ``--workdir``/``-w``, ``--timeout``, ``--host``, also as ``--name=value``)
|
|
584
|
+
are recognised only BEFORE the container; everything after the container word is the command, taken verbatim from the raw
|
|
585
|
+
command line and split like a shell line (quotes respected), including words that start with ``-``. The request's own
|
|
586
|
+
``args`` are not used when the raw line is there: its parser takes ``-a`` or ``-c`` of the command for options of this
|
|
587
|
+
command. Without a raw line (MCP, other clients) the parsed positionals and args are used."""
|
|
588
|
+
tokens = split_shell_words(command.raw_command or "")
|
|
589
|
+
if "exec" not in tokens:
|
|
590
|
+
return _exec_from_parsed_args(command)
|
|
591
|
+
result = _ExecInvocation()
|
|
592
|
+
start = tokens.index("exec")
|
|
593
|
+
# a host given before ``exec`` (``docker --host prod exec web ls``) is the command's own option
|
|
594
|
+
for k in range(start):
|
|
595
|
+
m0 = re.match(r"^--host(?:=(.*))?\Z", tokens[k], re.DOTALL)
|
|
596
|
+
if m0:
|
|
597
|
+
result.host = m0.group(1) if m0.group(1) is not None else (tokens[k + 1] if k + 1 < len(tokens) else None)
|
|
598
|
+
i = start + 1
|
|
599
|
+
while i < len(tokens):
|
|
600
|
+
m = _FLAG_WORD.match(tokens[i])
|
|
601
|
+
if not m:
|
|
602
|
+
break # the container
|
|
603
|
+
name = m.group(1)
|
|
604
|
+
inline = m.group(2)[1:] if m.group(2) is not None else None
|
|
605
|
+
if name in _INTERACTIVE_FLAGS and inline is None:
|
|
606
|
+
result.interactive = True
|
|
607
|
+
elif name in _EXEC_VALUE_FLAGS:
|
|
608
|
+
if inline is None:
|
|
609
|
+
i += 1
|
|
610
|
+
if i >= len(tokens):
|
|
611
|
+
break
|
|
612
|
+
value = tokens[i]
|
|
613
|
+
else:
|
|
614
|
+
value = inline
|
|
615
|
+
if name in ("user", "u"):
|
|
616
|
+
result.user = value
|
|
617
|
+
elif name in ("workdir", "w"):
|
|
618
|
+
result.workdir = value
|
|
619
|
+
elif name == "timeout":
|
|
620
|
+
result.timeout = value
|
|
621
|
+
else:
|
|
622
|
+
result.host = value
|
|
623
|
+
else:
|
|
624
|
+
break # an unknown option is taken as the container, which then does not exist: the error says so
|
|
625
|
+
i += 1
|
|
626
|
+
result.ref = tokens[i] if i < len(tokens) else None
|
|
627
|
+
result.words = tokens[i + 1:]
|
|
628
|
+
return result
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def _exec_from_parsed_args(command: CliProcessCommand) -> _ExecInvocation:
|
|
632
|
+
args = command.args or {}
|
|
633
|
+
|
|
634
|
+
def text(*keys: str) -> Optional[str]:
|
|
635
|
+
return next((args[k] for k in keys if isinstance(args.get(k), str) and args[k] != ""), None)
|
|
636
|
+
|
|
637
|
+
interactive = any(args.get(k) not in (None, False, "false") for k in _INTERACTIVE_FLAGS)
|
|
638
|
+
positionals = get_positionals(command)
|
|
639
|
+
timeout = args.get("timeout")
|
|
640
|
+
return _ExecInvocation(
|
|
641
|
+
interactive=interactive, host=_host_of(command), user=text("user", "u"), workdir=text("workdir", "w"),
|
|
642
|
+
timeout=None if timeout is None or timeout is True else str(timeout),
|
|
643
|
+
ref=positionals[0] if positionals else None, words=positionals[1:],
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
class _ExecProcessor(_DockerProcessor):
|
|
648
|
+
command = "exec"
|
|
649
|
+
description = "Runs a command in a running container and prints its output"
|
|
650
|
+
examples = [
|
|
651
|
+
CliCommandExample("docker exec web nginx -t", "Run a command"),
|
|
652
|
+
CliCommandExample("docker exec db ls -la /var/lib", "Everything after the container is the command, flags included"),
|
|
653
|
+
CliCommandExample('docker exec -u root web sh -c "echo a; exit 3"', "Options go before the container"),
|
|
654
|
+
CliCommandExample("docker exec -it web", "An interactive shell in the container"),
|
|
655
|
+
]
|
|
656
|
+
documentation = (
|
|
657
|
+
"docker exec [options] <container> [command...]. Options (-i, -t, -it, --interactive, --tty, --user/-u, --workdir/-w, "
|
|
658
|
+
"--timeout, --host) go BEFORE the container; everything after the container is the command, flags included "
|
|
659
|
+
'(docker exec web ls -la /, docker exec web sh -c "echo a; exit 3"). Without a command, or with -it, it opens an '
|
|
660
|
+
"interactive session in a web terminal."
|
|
661
|
+
)
|
|
662
|
+
value_required = True
|
|
663
|
+
required_permissions = [DOCKER_EXEC] # type: ignore[assignment]
|
|
664
|
+
parameters = [
|
|
665
|
+
_HOST,
|
|
666
|
+
CliCommandParameterDescriptor("user", "Run as this user", False, "string", aliases=["u"]),
|
|
667
|
+
CliCommandParameterDescriptor("workdir", "Working directory", False, "string", aliases=["w"]),
|
|
668
|
+
CliCommandParameterDescriptor("timeout", "Give up after this many seconds (1-300, default 30)", False, "number", default_value=30),
|
|
669
|
+
CliCommandParameterDescriptor("interactive", "Open an interactive session in the terminal", False, "boolean", aliases=["i"]),
|
|
670
|
+
CliCommandParameterDescriptor("tty", "Allocate a TTY (an interactive session always has one)", False, "boolean", aliases=["t"]),
|
|
671
|
+
CliCommandParameterDescriptor("it", "Short for --interactive --tty", False, "boolean"),
|
|
672
|
+
]
|
|
673
|
+
|
|
674
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
675
|
+
async def body() -> Optional[int]:
|
|
676
|
+
inv = _parse_exec(command)
|
|
677
|
+
interactive, ref, user = inv.interactive, inv.ref, inv.user
|
|
678
|
+
# one quoted word is a command line, as in the non-interactive form
|
|
679
|
+
words = split_shell_words(inv.words[0]) if len(inv.words) == 1 and re.search(r"\s", inv.words[0]) else inv.words
|
|
680
|
+
if not ref:
|
|
681
|
+
return _fail(out, "usage: docker exec [options] <container> [command...]")
|
|
682
|
+
if interactive or not words:
|
|
683
|
+
checked = await self.service.check_exec(inv.host, ref, _caller())
|
|
684
|
+
params: dict[str, str] = {"host": checked["host"], "container": checked["container"]["name"]}
|
|
685
|
+
if words:
|
|
686
|
+
params["cmd"] = " ".join(quote_shell_word(w) for w in words)
|
|
687
|
+
if user:
|
|
688
|
+
params["user"] = user
|
|
689
|
+
out.session(EXEC_SOCKET_PATH, params, title=checked["container"]["name"])
|
|
690
|
+
return 0
|
|
691
|
+
timeout: Optional[int] = None
|
|
692
|
+
if inv.timeout is not None:
|
|
693
|
+
try:
|
|
694
|
+
number = float(inv.timeout)
|
|
695
|
+
except ValueError:
|
|
696
|
+
number = float("nan")
|
|
697
|
+
if number != number or not number.is_integer() or number < 1 or number > 300:
|
|
698
|
+
return _fail(out, "Error: --timeout must be a whole number from 1 to 300")
|
|
699
|
+
timeout = int(number)
|
|
700
|
+
result = await self.service.exec(
|
|
701
|
+
inv.host, ref, {"command": words, "user": user, "workdir": inv.workdir, "timeoutSeconds": timeout}, _caller(),
|
|
702
|
+
)
|
|
703
|
+
if result["stdout"]:
|
|
704
|
+
out.text(re.sub(r"\n\Z", "", result["stdout"]))
|
|
705
|
+
if result["stderr"]:
|
|
706
|
+
out.text(re.sub(r"\n\Z", "", result["stderr"]), "warning")
|
|
707
|
+
if result["truncated"]:
|
|
708
|
+
out.warning("The output was cut at 1 MB.")
|
|
709
|
+
return result["exitCode"]
|
|
710
|
+
|
|
711
|
+
return await self._guarded(out, body)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
# -- images -------------------------------------------------------------------------------------------------------------
|
|
715
|
+
|
|
716
|
+
|
|
717
|
+
class _ImagesPruneProcessor(_DockerProcessor):
|
|
718
|
+
command = "prune"
|
|
719
|
+
description = "Removes dangling images (--all: every unused image)"
|
|
720
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
721
|
+
parameters = [_HOST, CliCommandParameterDescriptor("all", "Every unused image, not only dangling ones", False, "boolean", aliases=["a"]), _YES]
|
|
722
|
+
|
|
723
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
724
|
+
async def body() -> Optional[int]:
|
|
725
|
+
everything = _flag(command, "all", "a")
|
|
726
|
+
self.service.assert_writable()
|
|
727
|
+
if not await _confirmed(command, out, "Remove every unused image?" if everything else "Remove dangling images?"):
|
|
728
|
+
out.info("Nothing removed.")
|
|
729
|
+
return None
|
|
730
|
+
r = await self.service.prune_images(_host_of(command), all=everything, caller=_caller())
|
|
731
|
+
out.success(f"Removed {len(r['removed'])} item(s), reclaimed {format_bytes(r['reclaimedBytes'])}")
|
|
732
|
+
return None
|
|
733
|
+
|
|
734
|
+
return await self._guarded(out, body)
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
class _ImagesProcessor(_DockerProcessor):
|
|
738
|
+
command = "images"
|
|
739
|
+
description = "Lists images (images prune removes unused ones)"
|
|
740
|
+
parameters = [_HOST, _JSON]
|
|
741
|
+
|
|
742
|
+
def __init__(self, service: DockerService) -> None:
|
|
743
|
+
super().__init__(service)
|
|
744
|
+
self.processors = [_ImagesPruneProcessor(service)]
|
|
745
|
+
|
|
746
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
747
|
+
async def body() -> Optional[int]:
|
|
748
|
+
result = await self.service.images(_host_of(command))
|
|
749
|
+
if _flag(command, "json"):
|
|
750
|
+
return _print_json(out, result)
|
|
751
|
+
if not result["images"]:
|
|
752
|
+
out.info("No images.")
|
|
753
|
+
return None
|
|
754
|
+
out.table(
|
|
755
|
+
[[_names(i["tags"]) if i["tags"] else "<none>", i["shortId"], i["sizeBytes"], i["createdAt"], i["containers"]] for i in result["images"]],
|
|
756
|
+
[col.text("Image"), col.code("ID"), col.bytes("Size"), col.datetime("Created"), col.number("Used by")],
|
|
757
|
+
)
|
|
758
|
+
return None
|
|
759
|
+
|
|
760
|
+
return await self._guarded(out, body)
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
class _PullProcessor(_DockerProcessor):
|
|
764
|
+
command = "pull"
|
|
765
|
+
description = "Pulls an image"
|
|
766
|
+
examples = [CliCommandExample("docker pull busybox:musl")]
|
|
767
|
+
value_required = True
|
|
768
|
+
required_permissions = [DOCKER_MANAGE] # type: ignore[assignment]
|
|
769
|
+
|
|
770
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
771
|
+
async def body() -> Optional[int]:
|
|
772
|
+
refs = get_positionals(command)
|
|
773
|
+
if not refs:
|
|
774
|
+
return _fail(out, "name an image: docker pull <image>")
|
|
775
|
+
op = await self.service.pull(_host_of(command), refs[0], _caller())
|
|
776
|
+
ref = re.sub(r"^Pull ", "", op["title"])
|
|
777
|
+
return await _follow_operation(self.service, op, out, f"Pulling {ref}", f"Pulled {ref}", f"Could not pull {ref}")
|
|
778
|
+
|
|
779
|
+
return await self._guarded(out, body)
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
class _RmiProcessor(_DockerProcessor):
|
|
783
|
+
command = "rmi"
|
|
784
|
+
description = "Removes one or more images"
|
|
785
|
+
value_required = True
|
|
786
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
787
|
+
parameters = [_HOST, _force("Remove an image that containers use"), _YES]
|
|
788
|
+
|
|
789
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
790
|
+
async def body() -> Optional[int]:
|
|
791
|
+
refs = get_positionals(command)
|
|
792
|
+
if not refs:
|
|
793
|
+
return _fail(out, "name an image: docker rmi <image...>")
|
|
794
|
+
self.service.assert_writable()
|
|
795
|
+
if not await _confirmed(command, out, f"Remove {'image' if len(refs) == 1 else 'images'} {_names(refs)}?"):
|
|
796
|
+
out.info("Not removed.")
|
|
797
|
+
return None
|
|
798
|
+
code = 0
|
|
799
|
+
for ref in refs:
|
|
800
|
+
try:
|
|
801
|
+
await self.service.remove_image(_host_of(command), ref, force=_flag(command, "force"), caller=_caller())
|
|
802
|
+
out.success(f"{ref}: removed")
|
|
803
|
+
except Exception as err: # noqa: BLE001
|
|
804
|
+
code = 1
|
|
805
|
+
out.error(f"Error: {ref}: {err.message if isinstance(err, DockerError) else err}")
|
|
806
|
+
return code
|
|
807
|
+
|
|
808
|
+
return await self._guarded(out, body)
|
|
809
|
+
|
|
810
|
+
|
|
811
|
+
# -- stacks -------------------------------------------------------------------------------------------------------------
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
class _StacksShowProcessor(_DockerProcessor):
|
|
815
|
+
command = "show"
|
|
816
|
+
description = "Shows the containers of a stack and its compose file"
|
|
817
|
+
value_required = True
|
|
818
|
+
parameters = [_HOST, _JSON]
|
|
819
|
+
|
|
820
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
821
|
+
async def body() -> Optional[int]:
|
|
822
|
+
refs = get_positionals(command)
|
|
823
|
+
if not refs:
|
|
824
|
+
return _fail(out, "name a stack: docker stacks show <name>")
|
|
825
|
+
result = await self.service.stack(_host_of(command), refs[0])
|
|
826
|
+
if _flag(command, "json"):
|
|
827
|
+
return _print_json(out, result)
|
|
828
|
+
out.heading(f"Stack {result['stack']['name']} ({result['stack']['state']})", icon="server")
|
|
829
|
+
_write_containers(out, result["containers"], False)
|
|
830
|
+
if result["composeFile"]:
|
|
831
|
+
out.code(result["composeFile"]["content"], language="yaml", title=result["composeFile"]["path"])
|
|
832
|
+
return None
|
|
833
|
+
|
|
834
|
+
return await self._guarded(out, body)
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
class _StackActionProcessor(_DockerProcessor):
|
|
838
|
+
command = ""
|
|
839
|
+
description = ""
|
|
840
|
+
value_required = True
|
|
841
|
+
required_permissions = [DOCKER_MANAGE] # type: ignore[assignment]
|
|
842
|
+
|
|
843
|
+
def __init__(self, service: DockerService, action: str, aliases: Optional[list[str]] = None) -> None:
|
|
844
|
+
super().__init__(service)
|
|
845
|
+
self.action = action
|
|
846
|
+
self.command = action
|
|
847
|
+
self.aliases = list(aliases) if aliases else None
|
|
848
|
+
self.description = f"{action[0].upper()}{action[1:]}s the containers of a stack"
|
|
849
|
+
|
|
850
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
851
|
+
async def body() -> Optional[int]:
|
|
852
|
+
refs = get_positionals(command)
|
|
853
|
+
if not refs:
|
|
854
|
+
return _fail(out, f"name a stack: docker stacks {self.action} <name>")
|
|
855
|
+
result = await self.service.stack_action(_host_of(command), refs[0], self.action, _caller())
|
|
856
|
+
for r in result["results"]:
|
|
857
|
+
if r["ok"]:
|
|
858
|
+
out.success(f"{r['container']}: {_PAST[self.action]}")
|
|
859
|
+
else:
|
|
860
|
+
out.error(f"Error: {r['container']}: {r.get('error')}")
|
|
861
|
+
return 0 if result["ok"] else 1
|
|
862
|
+
|
|
863
|
+
return await self._guarded(out, body)
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
class _StackPullProcessor(_DockerProcessor):
|
|
867
|
+
command = "pull"
|
|
868
|
+
description = "Pulls the images of a stack"
|
|
869
|
+
value_required = True
|
|
870
|
+
required_permissions = [DOCKER_MANAGE] # type: ignore[assignment]
|
|
871
|
+
|
|
872
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
873
|
+
async def body() -> Optional[int]:
|
|
874
|
+
refs = get_positionals(command)
|
|
875
|
+
if not refs:
|
|
876
|
+
return _fail(out, "name a stack: docker stacks pull <name>")
|
|
877
|
+
name = refs[0]
|
|
878
|
+
op = await self.service.stack_pull(_host_of(command), name, _caller())
|
|
879
|
+
return await _follow_operation(
|
|
880
|
+
self.service, op, out, f"Pulling the images of {name}", f"Pulled the images of {name}", f"Could not pull the images of {name}",
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
return await self._guarded(out, body)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
class _StackDownProcessor(_DockerProcessor):
|
|
887
|
+
command = "down"
|
|
888
|
+
description = "Stops and removes the containers and networks of a stack (volumes stay unless --volumes)"
|
|
889
|
+
value_required = True
|
|
890
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
891
|
+
parameters = [_HOST, CliCommandParameterDescriptor("volumes", "Remove the stack's volumes too (a stack with a compose file)", False, "boolean", aliases=["v"]), _YES]
|
|
892
|
+
|
|
893
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
894
|
+
async def body() -> Optional[int]:
|
|
895
|
+
refs = get_positionals(command)
|
|
896
|
+
if not refs:
|
|
897
|
+
return _fail(out, "name a stack: docker stacks down <name>")
|
|
898
|
+
name = refs[0]
|
|
899
|
+
self.service.assert_writable()
|
|
900
|
+
shown = await self.service.stack(_host_of(command), name)
|
|
901
|
+
volumes = _flag(command, "volumes", "v")
|
|
902
|
+
if volumes and not shown["stack"].get("composeFile"):
|
|
903
|
+
return _fail(out, "volumes needs a compose file")
|
|
904
|
+
question = f"Remove the containers, networks and volumes of stack {name}?" if volumes else f"Remove the containers and networks of stack {name}?"
|
|
905
|
+
if not await _confirmed(command, out, question):
|
|
906
|
+
out.info("Not removed.")
|
|
907
|
+
return None
|
|
908
|
+
r = await self.service.stack_down(_host_of(command), name, _caller(), True if volumes else None)
|
|
909
|
+
if r["removedContainers"]:
|
|
910
|
+
out.success(f"Removed containers: {_names(r['removedContainers'])}")
|
|
911
|
+
if r["removedNetworks"]:
|
|
912
|
+
out.success(f"Removed networks: {_names(r['removedNetworks'])}")
|
|
913
|
+
for e in r["errors"]:
|
|
914
|
+
out.error(f"Error: {e}")
|
|
915
|
+
return 0 if r["ok"] else 1
|
|
916
|
+
|
|
917
|
+
return await self._guarded(out, body)
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
class _StackUpProcessor(_DockerProcessor):
|
|
921
|
+
command = "up"
|
|
922
|
+
description = "Deploys a stack from its compose file (docker compose up -d)"
|
|
923
|
+
value_required = True
|
|
924
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
925
|
+
parameters = [
|
|
926
|
+
_HOST,
|
|
927
|
+
CliCommandParameterDescriptor("file", "A compose file under composeRoots, for a stack that has none by the rule", False, "string"),
|
|
928
|
+
CliCommandParameterDescriptor("pull", "Pull the images first (--pull always)", False, "boolean"),
|
|
929
|
+
]
|
|
930
|
+
examples = [CliCommandExample("docker stacks up shop --pull")]
|
|
931
|
+
|
|
932
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
933
|
+
async def body() -> Optional[int]:
|
|
934
|
+
refs = get_positionals(command)
|
|
935
|
+
if not refs:
|
|
936
|
+
return _fail(out, "name a stack: docker stacks up <name>")
|
|
937
|
+
name = refs[0]
|
|
938
|
+
file = (command.args or {}).get("file")
|
|
939
|
+
body_: dict[str, Any] = {}
|
|
940
|
+
if isinstance(file, str) and file:
|
|
941
|
+
body_["file"] = file
|
|
942
|
+
if _flag(command, "pull"):
|
|
943
|
+
body_["pull"] = True
|
|
944
|
+
op = await self.service.up_stack(_host_of(command), name, body_, _caller())
|
|
945
|
+
code = await _follow_operation(self.service, op, out, f"Deploying stack {name}", f"Deployed stack {name}", f"Could not deploy stack {name}")
|
|
946
|
+
log = self.service.operation(op["id"], _caller())["operation"]["log"]
|
|
947
|
+
if code != 0 and log:
|
|
948
|
+
out.code("\n".join(log), title="Compose output")
|
|
949
|
+
return code
|
|
950
|
+
|
|
951
|
+
return await self._guarded(out, body)
|
|
952
|
+
|
|
953
|
+
|
|
954
|
+
class _StackRmProcessor(_DockerProcessor):
|
|
955
|
+
command = "rm"
|
|
956
|
+
description = "Deletes the compose file of a stack that is down"
|
|
957
|
+
value_required = True
|
|
958
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
959
|
+
parameters = [_HOST, _YES]
|
|
960
|
+
|
|
961
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
962
|
+
async def body() -> Optional[int]:
|
|
963
|
+
refs = get_positionals(command)
|
|
964
|
+
if not refs:
|
|
965
|
+
return _fail(out, "name a stack: docker stacks rm <name>")
|
|
966
|
+
name = refs[0]
|
|
967
|
+
self.service.assert_writable()
|
|
968
|
+
if not await _confirmed(command, out, f"Delete the compose file of stack {name}?"):
|
|
969
|
+
out.info("Not removed.")
|
|
970
|
+
return None
|
|
971
|
+
await self.service.delete_stack_compose(_host_of(command), name, _caller())
|
|
972
|
+
out.success(f"Deleted the compose file of stack {name}")
|
|
973
|
+
return None
|
|
974
|
+
|
|
975
|
+
return await self._guarded(out, body)
|
|
976
|
+
|
|
977
|
+
|
|
978
|
+
class _StacksProcessor(_DockerProcessor):
|
|
979
|
+
command = "stacks"
|
|
980
|
+
description = "Lists the compose stacks (the containers with a compose project label)"
|
|
981
|
+
aliases = ["stack", "compose"]
|
|
982
|
+
parameters = [_HOST, _JSON]
|
|
983
|
+
|
|
984
|
+
def __init__(self, service: DockerService) -> None:
|
|
985
|
+
super().__init__(service)
|
|
986
|
+
self.processors = [
|
|
987
|
+
_StacksShowProcessor(service), _StackUpProcessor(service), _StackActionProcessor(service, "start"), _StackActionProcessor(service, "stop"),
|
|
988
|
+
_StackActionProcessor(service, "restart"), _StackPullProcessor(service), _StackDownProcessor(service), _StackRmProcessor(service),
|
|
989
|
+
]
|
|
990
|
+
|
|
991
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
992
|
+
async def body() -> Optional[int]:
|
|
993
|
+
result = await self.service.stacks(_host_of(command))
|
|
994
|
+
if _flag(command, "json"):
|
|
995
|
+
return _print_json(out, result)
|
|
996
|
+
if not result["stacks"]:
|
|
997
|
+
out.info("No stacks.")
|
|
998
|
+
return None
|
|
999
|
+
out.table(
|
|
1000
|
+
[[s["name"], s["state"], s["containers"], _names(s["services"])] for s in result["stacks"]],
|
|
1001
|
+
[col.text("Name"), col.status("State", STACK_STATE_TONES), col.number("Containers"), col.text("Services")],
|
|
1002
|
+
row_command=[f"docker stacks show {s['name']}" for s in result["stacks"]],
|
|
1003
|
+
)
|
|
1004
|
+
return None
|
|
1005
|
+
|
|
1006
|
+
return await self._guarded(out, body)
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
# -- volumes and networks -----------------------------------------------------------------------------------------------
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
class _VolumesInspectProcessor(_DockerProcessor):
|
|
1013
|
+
command = "inspect"
|
|
1014
|
+
description = "Shows a volume"
|
|
1015
|
+
value_required = True
|
|
1016
|
+
parameters = [_HOST, _JSON]
|
|
1017
|
+
|
|
1018
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1019
|
+
async def body() -> Optional[int]:
|
|
1020
|
+
refs = get_positionals(command)
|
|
1021
|
+
if not refs:
|
|
1022
|
+
return _fail(out, "name a volume: docker volumes inspect <name>")
|
|
1023
|
+
result = await self.service.volume(_host_of(command), refs[0])
|
|
1024
|
+
if _flag(command, "json"):
|
|
1025
|
+
return _print_json(out, result)
|
|
1026
|
+
v = result["volume"]
|
|
1027
|
+
out.key_value([
|
|
1028
|
+
{"key": "Name", "value": v["name"]},
|
|
1029
|
+
{"key": "Driver", "value": v["driver"]},
|
|
1030
|
+
{"key": "Mountpoint", "value": v["mountpoint"]},
|
|
1031
|
+
{"key": "Created", "value": v["createdAt"], "type": "datetime"},
|
|
1032
|
+
{"key": "Stack", "value": v["stack"] or ""},
|
|
1033
|
+
{"key": "In use", "value": v["inUse"], "type": "bool"},
|
|
1034
|
+
{"key": "Labels", "value": [f"{k}={x}" for k, x in v["labels"].items()], "type": "tags"},
|
|
1035
|
+
])
|
|
1036
|
+
return None
|
|
1037
|
+
|
|
1038
|
+
return await self._guarded(out, body)
|
|
1039
|
+
|
|
1040
|
+
|
|
1041
|
+
class _VolumesCreateProcessor(_DockerProcessor):
|
|
1042
|
+
command = "create"
|
|
1043
|
+
description = "Creates a volume"
|
|
1044
|
+
value_required = True
|
|
1045
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
1046
|
+
parameters = [_HOST, CliCommandParameterDescriptor("driver", "The volume driver (default local)", False, "string", aliases=["d"])]
|
|
1047
|
+
|
|
1048
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1049
|
+
async def body() -> Optional[int]:
|
|
1050
|
+
refs = get_positionals(command)
|
|
1051
|
+
if not refs:
|
|
1052
|
+
return _fail(out, "name a volume: docker volumes create <name>")
|
|
1053
|
+
r = await self.service.create_volume(_host_of(command), {"name": refs[0], "driver": _str_arg(command, "driver", "d")}, _caller())
|
|
1054
|
+
out.success(f"Created volume {r['volume']['name']}")
|
|
1055
|
+
return None
|
|
1056
|
+
|
|
1057
|
+
return await self._guarded(out, body)
|
|
1058
|
+
|
|
1059
|
+
|
|
1060
|
+
class _VolumesRmProcessor(_DockerProcessor):
|
|
1061
|
+
command = "rm"
|
|
1062
|
+
description = "Removes one or more volumes"
|
|
1063
|
+
value_required = True
|
|
1064
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
1065
|
+
parameters = [_HOST, _force("Force the removal"), _YES]
|
|
1066
|
+
|
|
1067
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1068
|
+
async def body() -> Optional[int]:
|
|
1069
|
+
refs = get_positionals(command)
|
|
1070
|
+
if not refs:
|
|
1071
|
+
return _fail(out, "name a volume: docker volumes rm <name...>")
|
|
1072
|
+
self.service.assert_writable()
|
|
1073
|
+
if not await _confirmed(command, out, f"Remove {'volume' if len(refs) == 1 else 'volumes'} {_names(refs)}?"):
|
|
1074
|
+
out.info("Not removed.")
|
|
1075
|
+
return None
|
|
1076
|
+
code = 0
|
|
1077
|
+
for ref in refs:
|
|
1078
|
+
try:
|
|
1079
|
+
await self.service.remove_volume(_host_of(command), ref, force=_flag(command, "force"), caller=_caller())
|
|
1080
|
+
out.success(f"{ref}: removed")
|
|
1081
|
+
except Exception as err: # noqa: BLE001
|
|
1082
|
+
code = 1
|
|
1083
|
+
out.error(f"Error: {ref}: {err.message if isinstance(err, DockerError) else err}")
|
|
1084
|
+
return code
|
|
1085
|
+
|
|
1086
|
+
return await self._guarded(out, body)
|
|
1087
|
+
|
|
1088
|
+
|
|
1089
|
+
class _VolumesPruneProcessor(_DockerProcessor):
|
|
1090
|
+
command = "prune"
|
|
1091
|
+
description = "Removes the unused volumes"
|
|
1092
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
1093
|
+
parameters = [_HOST, _YES]
|
|
1094
|
+
|
|
1095
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1096
|
+
async def body() -> Optional[int]:
|
|
1097
|
+
self.service.assert_writable()
|
|
1098
|
+
if not await _confirmed(command, out, "Remove every unused volume?"):
|
|
1099
|
+
out.info("Nothing removed.")
|
|
1100
|
+
return None
|
|
1101
|
+
r = await self.service.prune_volumes(_host_of(command), _caller())
|
|
1102
|
+
out.success(f"Removed {len(r['removed'])} volume(s), reclaimed {format_bytes(r['reclaimedBytes'])}")
|
|
1103
|
+
return None
|
|
1104
|
+
|
|
1105
|
+
return await self._guarded(out, body)
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
class _VolumesProcessor(_DockerProcessor):
|
|
1109
|
+
command = "volumes"
|
|
1110
|
+
description = "Lists volumes"
|
|
1111
|
+
aliases = ["volume"]
|
|
1112
|
+
parameters = [_HOST, _JSON]
|
|
1113
|
+
|
|
1114
|
+
def __init__(self, service: DockerService) -> None:
|
|
1115
|
+
super().__init__(service)
|
|
1116
|
+
self.processors = [_VolumesInspectProcessor(service), _VolumesCreateProcessor(service), _VolumesRmProcessor(service), _VolumesPruneProcessor(service)]
|
|
1117
|
+
|
|
1118
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1119
|
+
async def body() -> Optional[int]:
|
|
1120
|
+
result = await self.service.volumes(_host_of(command))
|
|
1121
|
+
if _flag(command, "json"):
|
|
1122
|
+
return _print_json(out, result)
|
|
1123
|
+
if not result["volumes"]:
|
|
1124
|
+
out.info("No volumes.")
|
|
1125
|
+
return None
|
|
1126
|
+
out.table(
|
|
1127
|
+
[[v["name"], v["driver"], v["stack"] or "", v["inUse"], v["createdAt"]] for v in result["volumes"]],
|
|
1128
|
+
[col.text("Name"), col.text("Driver"), col.text("Stack"), col.bool("In use"), col.datetime("Created")],
|
|
1129
|
+
row_command=[f"docker volumes inspect {v['name']}" for v in result["volumes"]],
|
|
1130
|
+
)
|
|
1131
|
+
return None
|
|
1132
|
+
|
|
1133
|
+
return await self._guarded(out, body)
|
|
1134
|
+
|
|
1135
|
+
|
|
1136
|
+
class _NetworksInspectProcessor(_DockerProcessor):
|
|
1137
|
+
command = "inspect"
|
|
1138
|
+
description = "Shows a network and the containers attached to it"
|
|
1139
|
+
value_required = True
|
|
1140
|
+
parameters = [_HOST, _JSON]
|
|
1141
|
+
|
|
1142
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1143
|
+
async def body() -> Optional[int]:
|
|
1144
|
+
refs = get_positionals(command)
|
|
1145
|
+
if not refs:
|
|
1146
|
+
return _fail(out, "name a network: docker networks inspect <name>")
|
|
1147
|
+
result = await self.service.network(_host_of(command), refs[0])
|
|
1148
|
+
if _flag(command, "json"):
|
|
1149
|
+
return _print_json(out, result)
|
|
1150
|
+
n = result["network"]
|
|
1151
|
+
out.key_value([
|
|
1152
|
+
{"key": "Name", "value": n["name"]},
|
|
1153
|
+
{"key": "ID", "value": n["shortId"]},
|
|
1154
|
+
{"key": "Driver", "value": n["driver"]},
|
|
1155
|
+
{"key": "Scope", "value": n["scope"]},
|
|
1156
|
+
{"key": "Internal", "value": n["internal"], "type": "bool"},
|
|
1157
|
+
{"key": "Created", "value": n["createdAt"], "type": "datetime"},
|
|
1158
|
+
{"key": "Subnets", "value": n["subnets"], "type": "tags"},
|
|
1159
|
+
{"key": "Stack", "value": n["stack"] or ""},
|
|
1160
|
+
{"key": "Built-in", "value": n["builtin"], "type": "bool"},
|
|
1161
|
+
])
|
|
1162
|
+
if result["containers"]:
|
|
1163
|
+
out.table([[c["name"], c["ip"]] for c in result["containers"]], [col.text("Container"), col.text("IP")])
|
|
1164
|
+
return None
|
|
1165
|
+
|
|
1166
|
+
return await self._guarded(out, body)
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
class _NetworksCreateProcessor(_DockerProcessor):
|
|
1170
|
+
command = "create"
|
|
1171
|
+
description = "Creates a network"
|
|
1172
|
+
value_required = True
|
|
1173
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
1174
|
+
parameters = [
|
|
1175
|
+
_HOST,
|
|
1176
|
+
CliCommandParameterDescriptor("driver", "The network driver (default bridge)", False, "string", aliases=["d"]),
|
|
1177
|
+
CliCommandParameterDescriptor("internal", "No access to the outside", False, "boolean"),
|
|
1178
|
+
CliCommandParameterDescriptor("subnet", "The subnet as a CIDR, e.g. 10.20.0.0/24", False, "string"),
|
|
1179
|
+
]
|
|
1180
|
+
|
|
1181
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1182
|
+
async def body() -> Optional[int]:
|
|
1183
|
+
refs = get_positionals(command)
|
|
1184
|
+
if not refs:
|
|
1185
|
+
return _fail(out, "name a network: docker networks create <name>")
|
|
1186
|
+
subnet = command.args.get("subnet") if isinstance(command.args.get("subnet"), str) else None
|
|
1187
|
+
r = await self.service.create_network(
|
|
1188
|
+
_host_of(command), {"name": refs[0], "driver": _str_arg(command, "driver", "d"), "internal": True if _flag(command, "internal") else None, "subnet": subnet},
|
|
1189
|
+
_caller(),
|
|
1190
|
+
)
|
|
1191
|
+
out.success(f"Created network {r['network']['name']}")
|
|
1192
|
+
return None
|
|
1193
|
+
|
|
1194
|
+
return await self._guarded(out, body)
|
|
1195
|
+
|
|
1196
|
+
|
|
1197
|
+
class _NetworksRmProcessor(_DockerProcessor):
|
|
1198
|
+
command = "rm"
|
|
1199
|
+
description = "Removes one or more networks"
|
|
1200
|
+
value_required = True
|
|
1201
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
1202
|
+
parameters = [_HOST, _YES]
|
|
1203
|
+
|
|
1204
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1205
|
+
async def body() -> Optional[int]:
|
|
1206
|
+
refs = get_positionals(command)
|
|
1207
|
+
if not refs:
|
|
1208
|
+
return _fail(out, "name a network: docker networks rm <name...>")
|
|
1209
|
+
self.service.assert_writable()
|
|
1210
|
+
if not await _confirmed(command, out, f"Remove {'network' if len(refs) == 1 else 'networks'} {_names(refs)}?"):
|
|
1211
|
+
out.info("Not removed.")
|
|
1212
|
+
return None
|
|
1213
|
+
code = 0
|
|
1214
|
+
for ref in refs:
|
|
1215
|
+
try:
|
|
1216
|
+
await self.service.remove_network(_host_of(command), ref, _caller())
|
|
1217
|
+
out.success(f"{ref}: removed")
|
|
1218
|
+
except Exception as err: # noqa: BLE001
|
|
1219
|
+
code = 1
|
|
1220
|
+
out.error(f"Error: {ref}: {err.message if isinstance(err, DockerError) else err}")
|
|
1221
|
+
return code
|
|
1222
|
+
|
|
1223
|
+
return await self._guarded(out, body)
|
|
1224
|
+
|
|
1225
|
+
|
|
1226
|
+
class _NetworksPruneProcessor(_DockerProcessor):
|
|
1227
|
+
command = "prune"
|
|
1228
|
+
description = "Removes the unused networks"
|
|
1229
|
+
required_permissions = [DOCKER_ADMIN] # type: ignore[assignment]
|
|
1230
|
+
parameters = [_HOST, _YES]
|
|
1231
|
+
|
|
1232
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1233
|
+
async def body() -> Optional[int]:
|
|
1234
|
+
self.service.assert_writable()
|
|
1235
|
+
if not await _confirmed(command, out, "Remove every unused network?"):
|
|
1236
|
+
out.info("Nothing removed.")
|
|
1237
|
+
return None
|
|
1238
|
+
r = await self.service.prune_networks(_host_of(command), _caller())
|
|
1239
|
+
out.success(f"Removed {len(r['removed'])} network(s)")
|
|
1240
|
+
return None
|
|
1241
|
+
|
|
1242
|
+
return await self._guarded(out, body)
|
|
1243
|
+
|
|
1244
|
+
|
|
1245
|
+
class _NetworksProcessor(_DockerProcessor):
|
|
1246
|
+
command = "networks"
|
|
1247
|
+
description = "Lists networks"
|
|
1248
|
+
aliases = ["network"]
|
|
1249
|
+
parameters = [_HOST, _JSON]
|
|
1250
|
+
|
|
1251
|
+
def __init__(self, service: DockerService) -> None:
|
|
1252
|
+
super().__init__(service)
|
|
1253
|
+
self.processors = [_NetworksInspectProcessor(service), _NetworksCreateProcessor(service), _NetworksRmProcessor(service), _NetworksPruneProcessor(service)]
|
|
1254
|
+
|
|
1255
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1256
|
+
async def body() -> Optional[int]:
|
|
1257
|
+
result = await self.service.networks(_host_of(command))
|
|
1258
|
+
if _flag(command, "json"):
|
|
1259
|
+
return _print_json(out, result)
|
|
1260
|
+
out.table(
|
|
1261
|
+
[[n["name"], n["driver"], n["scope"], n["subnets"], n["containers"], n["stack"] or ""] for n in result["networks"]],
|
|
1262
|
+
[col.text("Name"), col.text("Driver"), col.text("Scope"), col.tags("Subnets"), col.number("Containers"), col.text("Stack")],
|
|
1263
|
+
row_command=[f"docker networks inspect {n['name']}" for n in result["networks"]],
|
|
1264
|
+
)
|
|
1265
|
+
return None
|
|
1266
|
+
|
|
1267
|
+
return await self._guarded(out, body)
|
|
1268
|
+
|
|
1269
|
+
|
|
1270
|
+
# -- system -------------------------------------------------------------------------------------------------------------
|
|
1271
|
+
|
|
1272
|
+
|
|
1273
|
+
class _SystemInfoProcessor(_DockerProcessor):
|
|
1274
|
+
command = "info"
|
|
1275
|
+
description = "Shows the Docker engine"
|
|
1276
|
+
parameters = [_HOST, _JSON]
|
|
1277
|
+
|
|
1278
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1279
|
+
async def body() -> Optional[int]:
|
|
1280
|
+
i = await self.service.info(_host_of(command))
|
|
1281
|
+
if _flag(command, "json"):
|
|
1282
|
+
return _print_json(out, i)
|
|
1283
|
+
out.key_value([
|
|
1284
|
+
{"key": "Host", "value": i["host"]},
|
|
1285
|
+
{"key": "Engine", "value": i["version"]},
|
|
1286
|
+
{"key": "API version", "value": i["apiVersion"]},
|
|
1287
|
+
{"key": "OS", "value": i["os"]},
|
|
1288
|
+
{"key": "Kernel", "value": i["kernel"]},
|
|
1289
|
+
{"key": "Architecture", "value": i["arch"]},
|
|
1290
|
+
{"key": "CPUs", "value": i["cpus"], "type": "number"},
|
|
1291
|
+
{"key": "Memory", "value": i["memoryBytes"], "type": "bytes"},
|
|
1292
|
+
{"key": "Name", "value": i["name"]},
|
|
1293
|
+
{"key": "Storage driver", "value": i["storageDriver"]},
|
|
1294
|
+
{"key": "Root directory", "value": i["rootDir"]},
|
|
1295
|
+
{"key": "Containers", "value": f"{i['containers']['running']} running, {i['containers']['paused']} paused, {i['containers']['stopped']} stopped"},
|
|
1296
|
+
{"key": "Images", "value": i["images"], "type": "number"},
|
|
1297
|
+
])
|
|
1298
|
+
return None
|
|
1299
|
+
|
|
1300
|
+
return await self._guarded(out, body)
|
|
1301
|
+
|
|
1302
|
+
|
|
1303
|
+
class _SystemDfProcessor(_DockerProcessor):
|
|
1304
|
+
command = "df"
|
|
1305
|
+
description = "Shows the disk usage of Docker and what can be reclaimed"
|
|
1306
|
+
parameters = [_HOST, _JSON]
|
|
1307
|
+
|
|
1308
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1309
|
+
async def body() -> Optional[int]:
|
|
1310
|
+
d = await self.service.df(_host_of(command))
|
|
1311
|
+
if _flag(command, "json"):
|
|
1312
|
+
return _print_json(out, d)
|
|
1313
|
+
kinds = [("Images", d["images"]), ("Containers", d["containers"]), ("Volumes", d["volumes"]), ("Build cache", d["buildCache"])]
|
|
1314
|
+
out.table(
|
|
1315
|
+
[[name, u["count"], u["sizeBytes"], u["reclaimableBytes"]] for name, u in kinds],
|
|
1316
|
+
[col.text("Type"), col.number("Count"), col.bytes("Size"), col.bytes("Reclaimable")],
|
|
1317
|
+
)
|
|
1318
|
+
return None
|
|
1319
|
+
|
|
1320
|
+
return await self._guarded(out, body)
|
|
1321
|
+
|
|
1322
|
+
|
|
1323
|
+
class _SystemEventsProcessor(_DockerProcessor):
|
|
1324
|
+
command = "events"
|
|
1325
|
+
description = "Shows the recent Docker events (--follow keeps streaming)"
|
|
1326
|
+
parameters = [
|
|
1327
|
+
_HOST,
|
|
1328
|
+
CliCommandParameterDescriptor("since", "How far back: 30s, 10m, 1h, 1d (default 1h, at most 1d)", False, "string", default_value="1h"),
|
|
1329
|
+
CliCommandParameterDescriptor("follow", "Keep streaming new events until stopped", False, "boolean", aliases=["f"]),
|
|
1330
|
+
_JSON,
|
|
1331
|
+
]
|
|
1332
|
+
|
|
1333
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1334
|
+
async def body() -> Optional[int]:
|
|
1335
|
+
parsed = {"seconds": 3600} if (command.args or {}).get("since") is None else _since_of(command, self.service.clock)
|
|
1336
|
+
if isinstance(parsed, str):
|
|
1337
|
+
return _fail(out, parsed)
|
|
1338
|
+
seconds = parsed.get("seconds") or 3600
|
|
1339
|
+
columns = [col.datetime("Time"), col.text("Type"), col.text("Action"), col.text("Name")]
|
|
1340
|
+
|
|
1341
|
+
def rows(events: list[dict[str, Any]]) -> list[list[Any]]:
|
|
1342
|
+
return [[e["time"], e["type"], e["action"], e["name"] or e["id"][:12]] for e in events]
|
|
1343
|
+
|
|
1344
|
+
result = await self.service.events(_host_of(command), since=seconds, limit=200)
|
|
1345
|
+
if _flag(command, "json"):
|
|
1346
|
+
return _print_json(out, result)
|
|
1347
|
+
if not result["events"]:
|
|
1348
|
+
out.info("No events.")
|
|
1349
|
+
else:
|
|
1350
|
+
out.table(rows(result["events"]), columns)
|
|
1351
|
+
if not _flag(command, "follow", "f"):
|
|
1352
|
+
return None
|
|
1353
|
+
if not out.interactive:
|
|
1354
|
+
return _fail(out, "--follow needs a streaming terminal")
|
|
1355
|
+
await self.service.follow_events(_host_of(command), 1, lambda events: out.table(rows(events), columns))
|
|
1356
|
+
return None
|
|
1357
|
+
|
|
1358
|
+
return await self._guarded(out, body)
|
|
1359
|
+
|
|
1360
|
+
|
|
1361
|
+
class _SystemProcessor(_DockerProcessor):
|
|
1362
|
+
command = "system"
|
|
1363
|
+
description = "The Docker engine: info, disk usage, events"
|
|
1364
|
+
|
|
1365
|
+
def __init__(self, service: DockerService) -> None:
|
|
1366
|
+
super().__init__(service)
|
|
1367
|
+
self.processors = [_SystemInfoProcessor(service), _SystemDfProcessor(service), _SystemEventsProcessor(service)]
|
|
1368
|
+
|
|
1369
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1370
|
+
_write_sub_commands(out, "docker system", self.description, self.processors)
|
|
1371
|
+
return 0
|
|
1372
|
+
|
|
1373
|
+
|
|
1374
|
+
# -- the root -----------------------------------------------------------------------------------------------------------
|
|
1375
|
+
|
|
1376
|
+
|
|
1377
|
+
class DockerRootProcessor(_DockerProcessor):
|
|
1378
|
+
command = "docker"
|
|
1379
|
+
description = "Docker containers, images, stacks, volumes and networks"
|
|
1380
|
+
module = "docker"
|
|
1381
|
+
icon = "🐳"
|
|
1382
|
+
required_permissions = [DOCKER_READ] # type: ignore[assignment]
|
|
1383
|
+
documentation = (
|
|
1384
|
+
"Manages the Docker hosts of the server through the Docker Engine API. Every command takes --host <name> (default local) and, "
|
|
1385
|
+
"where it prints data, --json. Containers can be hidden or protected and the plugin can be read-only (settings of the docker plugin)."
|
|
1386
|
+
)
|
|
1387
|
+
|
|
1388
|
+
def __init__(self, service: DockerService) -> None:
|
|
1389
|
+
super().__init__(service)
|
|
1390
|
+
self.processors = [
|
|
1391
|
+
_HostsProcessor(service), _PsProcessor(service), _InspectProcessor(service), _LogsProcessor(service), _StatsProcessor(service),
|
|
1392
|
+
*[_ActionProcessor(service, a) for a in CONTAINER_ACTIONS],
|
|
1393
|
+
_RmProcessor(service), _ExecProcessor(service), _ImagesProcessor(service), _PullProcessor(service), _RmiProcessor(service),
|
|
1394
|
+
_StacksProcessor(service), _VolumesProcessor(service), _NetworksProcessor(service), _SystemProcessor(service),
|
|
1395
|
+
]
|
|
1396
|
+
|
|
1397
|
+
async def handle_output(self, command: CliProcessCommand, out: CliOutput) -> int:
|
|
1398
|
+
async def body() -> Optional[int]:
|
|
1399
|
+
out.heading("Docker", icon="server")
|
|
1400
|
+
result = await self.service.hosts()
|
|
1401
|
+
hosts, read_only = result["hosts"], result["readOnly"]
|
|
1402
|
+
if not hosts:
|
|
1403
|
+
out.warning("No Docker host is configured: set endpoint in the docker settings.")
|
|
1404
|
+
else:
|
|
1405
|
+
_write_hosts(out, hosts)
|
|
1406
|
+
local = next((h for h in hosts if h["default"]), None)
|
|
1407
|
+
if local and local["reachable"]:
|
|
1408
|
+
info = await self.service.info(local["name"])
|
|
1409
|
+
out.key_value([
|
|
1410
|
+
{"key": "Engine", "value": info["version"]},
|
|
1411
|
+
{"key": "Containers", "value": f"{info['containers']['running']} running of {info['containers']['total']}"},
|
|
1412
|
+
{"key": "Images", "value": info["images"], "type": "number"},
|
|
1413
|
+
{"key": "Mode", "value": "read only" if read_only else "read-write"},
|
|
1414
|
+
])
|
|
1415
|
+
_write_sub_commands(out, "docker", "Commands", self.processors)
|
|
1416
|
+
return None
|
|
1417
|
+
|
|
1418
|
+
return await self._guarded(out, body)
|
|
1419
|
+
|
|
1420
|
+
|
|
1421
|
+
class DockerModule(CliModule):
|
|
1422
|
+
"""The ``docker`` commands as a module."""
|
|
1423
|
+
|
|
1424
|
+
name = "docker"
|
|
1425
|
+
version = "1.0.0"
|
|
1426
|
+
description = "Docker containers, images, stacks, volumes and networks"
|
|
1427
|
+
icon = "🐳"
|
|
1428
|
+
|
|
1429
|
+
def __init__(self, service: DockerService) -> None:
|
|
1430
|
+
self._processors: list[ICliCommandProcessor] = [DockerRootProcessor(service)]
|
|
1431
|
+
|
|
1432
|
+
@property
|
|
1433
|
+
def processors(self) -> Sequence[ICliCommandProcessor]: # type: ignore[override]
|
|
1434
|
+
return self._processors
|