docker-tiny-mcp 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docker_tiny_mcp/__init__.py +1 -0
- docker_tiny_mcp/__main__.py +280 -0
- docker_tiny_mcp/consent.py +252 -0
- docker_tiny_mcp/daemon.py +71 -0
- docker_tiny_mcp/errors.py +89 -0
- docker_tiny_mcp/events.py +51 -0
- docker_tiny_mcp/models.py +444 -0
- docker_tiny_mcp/prompts.py +58 -0
- docker_tiny_mcp/resources/__init__.py +15 -0
- docker_tiny_mcp/resources/containers.py +13 -0
- docker_tiny_mcp/resources/images.py +13 -0
- docker_tiny_mcp/resources/info.py +13 -0
- docker_tiny_mcp/resources/templates/__init__.py +11 -0
- docker_tiny_mcp/resources/templates/container.py +13 -0
- docker_tiny_mcp/resources/templates/logs.py +14 -0
- docker_tiny_mcp/safety.py +156 -0
- docker_tiny_mcp/server.py +115 -0
- docker_tiny_mcp/tools/__init__.py +57 -0
- docker_tiny_mcp/tools/container.py +104 -0
- docker_tiny_mcp/tools/containers.py +44 -0
- docker_tiny_mcp/tools/create.py +210 -0
- docker_tiny_mcp/tools/events.py +65 -0
- docker_tiny_mcp/tools/exec.py +99 -0
- docker_tiny_mcp/tools/images.py +71 -0
- docker_tiny_mcp/tools/info.py +51 -0
- docker_tiny_mcp/tools/logs.py +101 -0
- docker_tiny_mcp/tools/networks.py +59 -0
- docker_tiny_mcp/tools/prune.py +60 -0
- docker_tiny_mcp/tools/pull.py +36 -0
- docker_tiny_mcp/tools/read.py +69 -0
- docker_tiny_mcp/tools/remove.py +36 -0
- docker_tiny_mcp/tools/remove_image.py +37 -0
- docker_tiny_mcp/tools/restart.py +31 -0
- docker_tiny_mcp/tools/results.py +50 -0
- docker_tiny_mcp/tools/start.py +36 -0
- docker_tiny_mcp/tools/stats.py +124 -0
- docker_tiny_mcp/tools/stop.py +28 -0
- docker_tiny_mcp/tools/volumes.py +56 -0
- docker_tiny_mcp/tools/wait.py +57 -0
- docker_tiny_mcp/tools/write.py +76 -0
- docker_tiny_mcp-0.1.0.dist-info/METADATA +424 -0
- docker_tiny_mcp-0.1.0.dist-info/RECORD +45 -0
- docker_tiny_mcp-0.1.0.dist-info/WHEEL +4 -0
- docker_tiny_mcp-0.1.0.dist-info/entry_points.txt +3 -0
- docker_tiny_mcp-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Removing one image.
|
|
2
|
+
|
|
3
|
+
The daemon refuses where a container still holds it, which is the check worth
|
|
4
|
+
having; `force` overrides that and leaves the container unable to start again,
|
|
5
|
+
which is why the tool says so rather than offering it quietly.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from aiodocker import Docker
|
|
11
|
+
from aiohttp_tiny_mcp import Exchange
|
|
12
|
+
|
|
13
|
+
from docker_tiny_mcp.consent import Policy, confirm, refusal
|
|
14
|
+
from docker_tiny_mcp.errors import clear
|
|
15
|
+
from docker_tiny_mcp.events import publish
|
|
16
|
+
from docker_tiny_mcp.models import ImageRef
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def remove_image(args: ImageRef, client: Docker, ex: Exchange, policy: Policy) -> str:
|
|
20
|
+
"""Remove an image, reclaiming its space. Asks before it does.
|
|
21
|
+
|
|
22
|
+
Check `images` first: an image another container holds is refused unless
|
|
23
|
+
`force` is set, and forcing it leaves that container unable to start
|
|
24
|
+
again.
|
|
25
|
+
"""
|
|
26
|
+
if not await confirm(
|
|
27
|
+
ex,
|
|
28
|
+
policy,
|
|
29
|
+
"remove_image",
|
|
30
|
+
args.image,
|
|
31
|
+
f"Remove image {args.image}? This cannot be undone.",
|
|
32
|
+
):
|
|
33
|
+
return f"not removed: {refusal(ex)}"
|
|
34
|
+
async with clear("removing the image", subject=args.image):
|
|
35
|
+
removed = await client.images.delete(args.image, force=args.force)
|
|
36
|
+
await publish(ex.registry, "docker://images")
|
|
37
|
+
return f"removed {args.image} ({len(removed)} layers untagged or deleted)"
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Stopping and starting, which is the usual first thing to try.
|
|
2
|
+
|
|
3
|
+
Like `start`, it reports the state a moment later, because the container that
|
|
4
|
+
comes back up is not always the one that went down.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from aiodocker import Docker
|
|
10
|
+
from aiohttp_tiny_mcp import Exchange
|
|
11
|
+
|
|
12
|
+
from docker_tiny_mcp import daemon
|
|
13
|
+
from docker_tiny_mcp.events import publish
|
|
14
|
+
from docker_tiny_mcp.models import Done, StopRequest
|
|
15
|
+
from docker_tiny_mcp.safety import checked_container
|
|
16
|
+
|
|
17
|
+
from .results import outcome, settled
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def restart(args: StopRequest, client: Docker, ex: Exchange) -> Done:
|
|
21
|
+
"""Stop and start a container. The usual first thing to try."""
|
|
22
|
+
found = await daemon.find(client, args.container)
|
|
23
|
+
await found.restart(timeout=args.seconds)
|
|
24
|
+
await publish(ex.registry, "docker://containers")
|
|
25
|
+
return outcome(args.container, "restart", await settled(found), "running")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
async def restart_unprivileged(args: StopRequest, client: Docker, ex: Exchange) -> Done:
|
|
29
|
+
"""Restart a container after checking that it has no host access."""
|
|
30
|
+
identity = await checked_container(client, args.container)
|
|
31
|
+
return await restart(args.model_copy(update={"container": identity}), client, ex)
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""What a change achieved, rather than what it was asked to do."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from aiodocker.containers import DockerContainer
|
|
9
|
+
|
|
10
|
+
from docker_tiny_mcp import daemon
|
|
11
|
+
from docker_tiny_mcp.models import Done
|
|
12
|
+
|
|
13
|
+
SETTLE_SECONDS = 0.4
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
async def settled(container: DockerContainer) -> dict[str, Any]:
|
|
17
|
+
"""Read the state a moment after a change, rather than during it."""
|
|
18
|
+
await asyncio.sleep(SETTLE_SECONDS)
|
|
19
|
+
return await daemon.state_of(container)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def outcome(name: str, action: str, state: dict[str, Any], wanted: str) -> Done:
|
|
23
|
+
"""Report what a change achieved, not only that it was asked for.
|
|
24
|
+
|
|
25
|
+
A container that starts and dies within the second is the case this exists
|
|
26
|
+
for. Reporting `state` alone is true and useless: the caller then spends
|
|
27
|
+
two more calls learning what this already knows.
|
|
28
|
+
"""
|
|
29
|
+
status = str(state.get("Status", "unknown"))
|
|
30
|
+
health = (state.get("Health") or {}).get("Status")
|
|
31
|
+
code = state.get("ExitCode")
|
|
32
|
+
exit_code = int(code) if code is not None and status != "running" else None
|
|
33
|
+
note = None
|
|
34
|
+
if wanted == "running" and status != "running":
|
|
35
|
+
note = f"it did not stay running: it is {status}"
|
|
36
|
+
if exit_code is not None:
|
|
37
|
+
note += f", having exited with {exit_code}. Read `logs` for why"
|
|
38
|
+
elif health == "unhealthy":
|
|
39
|
+
note = "it runs, but its own health check says it is unhealthy"
|
|
40
|
+
return Done(
|
|
41
|
+
container=name,
|
|
42
|
+
action=action,
|
|
43
|
+
state=status,
|
|
44
|
+
exit_code=exit_code,
|
|
45
|
+
health=str(health) if health else None,
|
|
46
|
+
note=note,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
__all__ = ["SETTLE_SECONDS", "outcome", "settled"]
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Starting a container, and reporting what became of it.
|
|
2
|
+
|
|
3
|
+
Docker answers before the process inside is up, so the state is read a moment
|
|
4
|
+
later. A container that starts and dies at once is reported as dead, with its
|
|
5
|
+
exit code, instead of being reported as started.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from aiodocker import Docker
|
|
11
|
+
from aiohttp_tiny_mcp import Exchange
|
|
12
|
+
|
|
13
|
+
from docker_tiny_mcp import daemon
|
|
14
|
+
from docker_tiny_mcp.events import publish
|
|
15
|
+
from docker_tiny_mcp.models import ContainerRef, Done
|
|
16
|
+
from docker_tiny_mcp.safety import checked_container
|
|
17
|
+
|
|
18
|
+
from .results import outcome, settled
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
async def start(args: ContainerRef, client: Docker, ex: Exchange) -> Done:
|
|
22
|
+
"""Start a stopped container. Starting a running one changes nothing.
|
|
23
|
+
|
|
24
|
+
Reports the state a moment later, so a container that starts and dies at
|
|
25
|
+
once is reported as dead rather than as started.
|
|
26
|
+
"""
|
|
27
|
+
found = await daemon.find(client, args.container)
|
|
28
|
+
await found.start()
|
|
29
|
+
await publish(ex.registry, "docker://containers")
|
|
30
|
+
return outcome(args.container, "start", await settled(found), "running")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
async def start_unprivileged(args: ContainerRef, client: Docker, ex: Exchange) -> Done:
|
|
34
|
+
"""Start a container after checking that it has no host access."""
|
|
35
|
+
identity = await checked_container(client, args.container)
|
|
36
|
+
return await start(args.model_copy(update={"container": identity}), client, ex)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""What a container is using, as a rate.
|
|
2
|
+
|
|
3
|
+
The counters are totals since it started, so one reading answers nothing. The
|
|
4
|
+
arithmetic between two of them lives in `docker.py`; what this file decides is
|
|
5
|
+
that a tool must pay for the second reading rather than return a number that
|
|
6
|
+
looks like a rate and is not.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
from collections.abc import AsyncGenerator, Mapping
|
|
13
|
+
from typing import Any, cast
|
|
14
|
+
|
|
15
|
+
from aiodocker import Docker
|
|
16
|
+
from aiodocker.containers import DockerContainer
|
|
17
|
+
|
|
18
|
+
from docker_tiny_mcp import daemon
|
|
19
|
+
from docker_tiny_mcp.errors import Timeout, clear
|
|
20
|
+
from docker_tiny_mcp.models import ContainerRef, Stats
|
|
21
|
+
|
|
22
|
+
SAMPLE_SECONDS = 3.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def megabytes(value: Any) -> float:
|
|
26
|
+
return round(float(value or 0) / 1_000_000, 1)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def rate(now: Mapping[str, Any], before: Mapping[str, Any]) -> float:
|
|
30
|
+
"""Processor use as a percentage of one core, from two samples.
|
|
31
|
+
|
|
32
|
+
A single sample cannot state a rate: the counters are totals since the
|
|
33
|
+
container started. This is the arithmetic `docker stats` does, and it is
|
|
34
|
+
why `stats` reads twice.
|
|
35
|
+
"""
|
|
36
|
+
cpu = now.get("cpu_stats") or {}
|
|
37
|
+
past = before.get("cpu_stats") or before.get("precpu_stats") or {}
|
|
38
|
+
used = float((cpu.get("cpu_usage") or {}).get("total_usage", 0) or 0) - float(
|
|
39
|
+
(past.get("cpu_usage") or {}).get("total_usage", 0) or 0
|
|
40
|
+
)
|
|
41
|
+
system = float(cpu.get("system_cpu_usage", 0) or 0) - float(
|
|
42
|
+
past.get("system_cpu_usage", 0) or 0
|
|
43
|
+
)
|
|
44
|
+
cores = float(cpu.get("online_cpus", 0) or 0) or len(
|
|
45
|
+
(cpu.get("cpu_usage") or {}).get("percpu_usage") or []
|
|
46
|
+
)
|
|
47
|
+
if used <= 0 or system <= 0:
|
|
48
|
+
return 0.0
|
|
49
|
+
return round(used / system * (cores or 1) * 100, 1)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def blocks(raw: Mapping[str, Any]) -> tuple[float, float]:
|
|
53
|
+
"""Bytes read from and written to disk. The daemon capitalises the
|
|
54
|
+
operation one way on cgroup v1 and the other on v2."""
|
|
55
|
+
entries = (raw.get("blkio_stats") or {}).get("io_service_bytes_recursive") or []
|
|
56
|
+
|
|
57
|
+
def total(operation: str) -> float:
|
|
58
|
+
return sum(
|
|
59
|
+
float(item.get("value", 0) or 0)
|
|
60
|
+
for item in entries
|
|
61
|
+
if str(item.get("op", "")).lower() == operation
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
return megabytes(total("read")), megabytes(total("write"))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def stats_of(name: str, now: Mapping[str, Any], before: Mapping[str, Any]) -> Stats:
|
|
68
|
+
memory = now.get("memory_stats") or {}
|
|
69
|
+
used = float(memory.get("usage", 0) or 0)
|
|
70
|
+
limit = float(memory.get("limit", 0) or 0)
|
|
71
|
+
networks = (now.get("networks") or {}).values()
|
|
72
|
+
read, written = blocks(now)
|
|
73
|
+
return Stats(
|
|
74
|
+
container=name,
|
|
75
|
+
cpu_percent=rate(now, before),
|
|
76
|
+
memory_mb=megabytes(used),
|
|
77
|
+
memory_limit_mb=megabytes(limit),
|
|
78
|
+
memory_percent=round(used / limit * 100, 1) if limit else 0.0,
|
|
79
|
+
net_rx_mb=megabytes(sum(float(item.get("rx_bytes", 0) or 0) for item in networks)),
|
|
80
|
+
net_tx_mb=megabytes(sum(float(item.get("tx_bytes", 0) or 0) for item in networks)),
|
|
81
|
+
block_read_mb=read,
|
|
82
|
+
block_write_mb=written,
|
|
83
|
+
pids=int(((now.get("pids_stats") or {}).get("current")) or 0),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
async def samples(container: DockerContainer, name: str) -> Stats:
|
|
88
|
+
"""Read the counters twice and report the rate between. Give up rather than hold the call
|
|
89
|
+
open, because a container that stops mid-read stops answering.
|
|
90
|
+
"""
|
|
91
|
+
taken: list[Mapping[str, Any]] = []
|
|
92
|
+
# aiodocker types this as an iterator, and returns an async generator: the
|
|
93
|
+
# call below closes it, so the stream does not outlive this function.
|
|
94
|
+
stream = cast(AsyncGenerator[Mapping[str, Any], None], container.stats(stream=True))
|
|
95
|
+
|
|
96
|
+
async def collect() -> None:
|
|
97
|
+
async for sample in stream:
|
|
98
|
+
taken.append(sample)
|
|
99
|
+
if len(taken) == 2:
|
|
100
|
+
return
|
|
101
|
+
|
|
102
|
+
async with clear("reading the counters", subject=name):
|
|
103
|
+
try:
|
|
104
|
+
await asyncio.wait_for(collect(), SAMPLE_SECONDS)
|
|
105
|
+
except (asyncio.TimeoutError, StopAsyncIteration):
|
|
106
|
+
pass
|
|
107
|
+
finally:
|
|
108
|
+
await stream.aclose()
|
|
109
|
+
if not taken:
|
|
110
|
+
raise Timeout(f"{name} reported no counters within {SAMPLE_SECONDS:.0f} seconds")
|
|
111
|
+
if len(taken) == 1:
|
|
112
|
+
return stats_of(name, taken[0], {"cpu_stats": taken[0].get("precpu_stats") or {}})
|
|
113
|
+
return stats_of(name, taken[1], taken[0])
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
async def stats(args: ContainerRef, client: Docker) -> Stats:
|
|
117
|
+
"""What one container is using now: processor, memory, network and disk.
|
|
118
|
+
|
|
119
|
+
Two readings a moment apart, because a rate cannot be had from one. Use
|
|
120
|
+
this for "why is this machine busy" and for a container suspected of
|
|
121
|
+
leaking memory -- read it twice, minutes apart, and compare.
|
|
122
|
+
"""
|
|
123
|
+
found = await daemon.find(client, args.container)
|
|
124
|
+
return await samples(found, args.container)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""Stopping a container, with time to finish first.
|
|
2
|
+
|
|
3
|
+
The state is read straight after rather than after a pause: `stop` already
|
|
4
|
+
waited, and there is nothing left to settle.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from aiodocker import Docker
|
|
10
|
+
from aiohttp_tiny_mcp import Exchange
|
|
11
|
+
|
|
12
|
+
from docker_tiny_mcp import daemon
|
|
13
|
+
from docker_tiny_mcp.events import publish
|
|
14
|
+
from docker_tiny_mcp.models import Done, StopRequest
|
|
15
|
+
|
|
16
|
+
from .results import outcome
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def stop(args: StopRequest, client: Docker, ex: Exchange) -> Done:
|
|
20
|
+
"""Stop a running container, giving it `seconds` to finish first.
|
|
21
|
+
|
|
22
|
+
It is killed if it has not stopped by then. Stopping a stopped container
|
|
23
|
+
changes nothing.
|
|
24
|
+
"""
|
|
25
|
+
found = await daemon.find(client, args.container)
|
|
26
|
+
await found.stop(t=args.seconds)
|
|
27
|
+
await publish(ex.registry, "docker://containers")
|
|
28
|
+
return outcome(args.container, "stop", await daemon.state_of(found), "exited")
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Volumes, and what mounts them.
|
|
2
|
+
|
|
3
|
+
An empty `used_by` is not the same as waste. It is either space to reclaim or
|
|
4
|
+
a database whose container is gone, and only the name tells the two apart --
|
|
5
|
+
which is why this reports and never removes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from collections.abc import Mapping, Sequence
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from aiodocker import Docker
|
|
14
|
+
|
|
15
|
+
from docker_tiny_mcp import daemon
|
|
16
|
+
from docker_tiny_mcp.errors import clear
|
|
17
|
+
from docker_tiny_mcp.models import NameFilter, Volume, Volumes
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def mounters(containers: Sequence[dict[str, Any]]) -> dict[str, list[str]]:
|
|
21
|
+
"""Which containers mount which named volume."""
|
|
22
|
+
found: dict[str, list[str]] = {}
|
|
23
|
+
for raw in containers:
|
|
24
|
+
name = daemon.name_of(raw)
|
|
25
|
+
for mount in raw.get("Mounts") or []:
|
|
26
|
+
if mount.get("Type") == "volume" and mount.get("Name"):
|
|
27
|
+
found.setdefault(str(mount["Name"]), []).append(name)
|
|
28
|
+
return found
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def volume_of(raw: dict[str, Any], users: Mapping[str, list[str]] | None = None) -> Volume:
|
|
32
|
+
name = str(raw.get("Name", ""))
|
|
33
|
+
return Volume(
|
|
34
|
+
name=name,
|
|
35
|
+
driver=str(raw.get("Driver", "")),
|
|
36
|
+
mountpoint=str(raw.get("Mountpoint", "")),
|
|
37
|
+
created=daemon.when(raw.get("CreatedAt")),
|
|
38
|
+
used_by=sorted((users or {}).get(name, [])),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def volumes(args: NameFilter, client: Docker) -> Volumes:
|
|
43
|
+
"""List volumes, and which containers mount them.
|
|
44
|
+
|
|
45
|
+
`used_by` is empty where a volume holds data nothing is reading -- which
|
|
46
|
+
is either space to reclaim or a service that lost its data, so read the
|
|
47
|
+
name before removing it.
|
|
48
|
+
"""
|
|
49
|
+
users = mounters(await daemon.containers(client, all=True))
|
|
50
|
+
async with clear("listing volumes"):
|
|
51
|
+
found = await client.volumes.list()
|
|
52
|
+
listed = [volume_of(dict(raw), users) for raw in found.get("Volumes") or []]
|
|
53
|
+
if args.name:
|
|
54
|
+
wanted = args.name.lower()
|
|
55
|
+
listed = [item for item in listed if wanted in item.name.lower()]
|
|
56
|
+
return Volumes(volumes=listed, total=len(listed))
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Holding until a container is what was asked for.
|
|
2
|
+
|
|
3
|
+
A reading tool, although it is used between two changing ones: all it does is
|
|
4
|
+
read the state until the answer is the one wanted. `docker.wait_for` polls
|
|
5
|
+
rather than using the daemon's own `wait`, which knows only about stopping and
|
|
6
|
+
cannot report a container becoming healthy.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from aiodocker import Docker
|
|
15
|
+
from aiodocker.containers import DockerContainer
|
|
16
|
+
|
|
17
|
+
from docker_tiny_mcp import daemon
|
|
18
|
+
from docker_tiny_mcp.errors import Timeout
|
|
19
|
+
from docker_tiny_mcp.models import Done, WaitRequest
|
|
20
|
+
|
|
21
|
+
from .results import outcome
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
async def wait_for(
|
|
25
|
+
container: DockerContainer, name: str, state: str, seconds: int
|
|
26
|
+
) -> dict[str, Any]:
|
|
27
|
+
"""Poll until the container reaches `state`, or time runs out.
|
|
28
|
+
|
|
29
|
+
The daemon's own `wait` knows only about stopping and cannot report a container becoming
|
|
30
|
+
healthy.
|
|
31
|
+
"""
|
|
32
|
+
loop = asyncio.get_running_loop()
|
|
33
|
+
deadline = loop.time() + seconds
|
|
34
|
+
while True:
|
|
35
|
+
current = await daemon.state_of(container)
|
|
36
|
+
status = str(current.get("Status", "unknown"))
|
|
37
|
+
health = str((current.get("Health") or {}).get("Status") or "")
|
|
38
|
+
if state == "healthy" and health == "healthy":
|
|
39
|
+
return current
|
|
40
|
+
if state != "healthy" and status == state:
|
|
41
|
+
return current
|
|
42
|
+
if loop.time() >= deadline:
|
|
43
|
+
said = f"{status}, health {health}" if health else status
|
|
44
|
+
raise Timeout(f"{name} was still {said} after {seconds} seconds")
|
|
45
|
+
await asyncio.sleep(0.25)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def wait(args: WaitRequest, client: Docker) -> Done:
|
|
49
|
+
"""Wait until a container is running, stopped, or reports itself healthy.
|
|
50
|
+
|
|
51
|
+
Use this instead of asking for its state in a loop: a container with a
|
|
52
|
+
health check takes seconds to become healthy, and reading too early says
|
|
53
|
+
"starting" and means nothing.
|
|
54
|
+
"""
|
|
55
|
+
found = await daemon.find(client, args.container)
|
|
56
|
+
state = await wait_for(found, args.container, args.state, args.seconds)
|
|
57
|
+
return outcome(args.container, f"wait for {args.state}", state, args.state)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Putting one file inside a container.
|
|
2
|
+
|
|
3
|
+
The daemon takes a tar archive extracted into a directory, so the smallest
|
|
4
|
+
write is still an archive of one member; `docker.write_file` builds it. Works
|
|
5
|
+
on a stopped container, which is what makes a broken configuration fixable
|
|
6
|
+
before the next start.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import io
|
|
12
|
+
import tarfile
|
|
13
|
+
import time
|
|
14
|
+
|
|
15
|
+
from aiodocker import Docker
|
|
16
|
+
from aiodocker.containers import DockerContainer
|
|
17
|
+
from aiohttp_tiny_mcp import Exchange
|
|
18
|
+
|
|
19
|
+
from docker_tiny_mcp import daemon
|
|
20
|
+
from docker_tiny_mcp.consent import Policy, confirm, refusal
|
|
21
|
+
from docker_tiny_mcp.errors import Conflict, clear
|
|
22
|
+
from docker_tiny_mcp.models import WriteRequest, Written
|
|
23
|
+
from docker_tiny_mcp.safety import checked_container
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
async def write_file(container: DockerContainer, path: str, content: bytes, mode: int) -> None:
|
|
27
|
+
"""Write one file. The daemon extracts a tar archive into a directory, so the smallest write
|
|
28
|
+
is an archive of one member.
|
|
29
|
+
"""
|
|
30
|
+
directory, _, name = path.rpartition("/")
|
|
31
|
+
if not name:
|
|
32
|
+
raise Conflict(f"{path} names a directory, not a file")
|
|
33
|
+
buffer = io.BytesIO()
|
|
34
|
+
with tarfile.open(fileobj=buffer, mode="w") as archive:
|
|
35
|
+
entry = tarfile.TarInfo(name=name)
|
|
36
|
+
entry.size = len(content)
|
|
37
|
+
entry.mode = mode
|
|
38
|
+
entry.mtime = int(time.time())
|
|
39
|
+
archive.addfile(entry, io.BytesIO(content))
|
|
40
|
+
async with clear("writing the file", subject=path):
|
|
41
|
+
await container.put_archive(directory or "/", buffer.getvalue())
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def write(args: WriteRequest, client: Docker, ex: Exchange, policy: Policy) -> Written:
|
|
45
|
+
"""Write one file inside a container, creating or replacing it.
|
|
46
|
+
|
|
47
|
+
Works on a stopped container, so a broken configuration can be corrected
|
|
48
|
+
before starting it again. The file goes away with the container unless the
|
|
49
|
+
path is on a volume, which is why the default policy does not ask before
|
|
50
|
+
replacing it.
|
|
51
|
+
"""
|
|
52
|
+
found = await daemon.find(client, args.container)
|
|
53
|
+
if not await confirm(
|
|
54
|
+
ex,
|
|
55
|
+
policy,
|
|
56
|
+
"write",
|
|
57
|
+
args.container,
|
|
58
|
+
f"Write {len(args.content)} bytes to {args.path} inside {args.container}? "
|
|
59
|
+
"Whatever is there now is replaced.",
|
|
60
|
+
):
|
|
61
|
+
raise Conflict(f"not written: {refusal(ex)}")
|
|
62
|
+
content = args.content.encode("utf-8")
|
|
63
|
+
await write_file(found, args.path, content, int(args.mode, 8))
|
|
64
|
+
state = await daemon.state_of(found)
|
|
65
|
+
note = None
|
|
66
|
+
if str(state.get("Status")) == "running":
|
|
67
|
+
note = "the container is running: restart it if it reads this file only at startup"
|
|
68
|
+
return Written(container=args.container, path=args.path, size_bytes=len(content), note=note)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
async def write_unprivileged(
|
|
72
|
+
args: WriteRequest, client: Docker, ex: Exchange, policy: Policy
|
|
73
|
+
) -> Written:
|
|
74
|
+
"""Write a file after checking that the container has no host access."""
|
|
75
|
+
identity = await checked_container(client, args.container)
|
|
76
|
+
return await write(args.model_copy(update={"container": identity}), client, ex, policy)
|