Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement container.commit() command #418

Merged
merged 5 commits into from
Mar 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
1 change: 1 addition & 0 deletions CHANGES/418.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Implement container commit, pause and unpause functionality.
47 changes: 46 additions & 1 deletion aiodocker/containers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import json
import shlex
import tarfile
from typing import Mapping, Optional, Sequence, Tuple, Union
from typing import Any, Dict, Mapping, Optional, Sequence, Tuple, Union

from multidict import MultiDict
from yarl import URL
Expand Down Expand Up @@ -109,6 +109,10 @@ def __init__(self, docker, **kwargs):
)
self.logs = DockerLog(docker, self)

@property
def id(self) -> str:
return self._id

def log(self, *, stdout=False, stderr=False, follow=False, **kwargs):
if stdout is False and stderr is False:
raise TypeError("Need one of stdout or stderr")
Expand Down Expand Up @@ -347,6 +351,47 @@ async def resize(self, *, h: int, w: int) -> None:
url = URL(f"containers/{self._id}/resize").with_query(h=h, w=w)
await self.docker._query_json(url, method="POST")

async def commit(
self,
*,
repository: Optional[str] = None,
tag: Optional[str] = None,
message: Optional[str] = None,
author: Optional[str] = None,
changes: Optional[Union[str, Sequence[str]]] = None,
config: Optional[Dict[str, Any]] = None,
pause: bool = True,
) -> Dict[str, Any]:
"""
Commit a container to an image. Similar to the ``docker commit``
command.
"""
params = {"container": self._id, "pause": pause}
if repository is not None:
params["repo"] = repository
if tag is not None:
params["tag"] = tag
if message is not None:
params["comment"] = message
if author is not None:
params["author"] = author
if changes is not None:
if not isinstance(changes, str):
changes = "\n".join(changes)
params["changes"] = changes

return await self.docker._query_json(
"commit", method="POST", params=params, data=config
)

async def pause(self) -> None:
async with self.docker._query(f"containers/{self._id}/pause", method="POST"):
pass

async def unpause(self) -> None:
async with self.docker._query(f"containers/{self._id}/unpause", method="POST"):
pass

def __getitem__(self, key):
return self._container[key]

Expand Down
60 changes: 60 additions & 0 deletions tests/test_containers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import os
import sys

import pytest

Expand Down Expand Up @@ -162,3 +163,62 @@ async def test_container_stats_stream(docker, image_name):
@pytest.mark.asyncio
async def test_resize(shell_container):
await shell_container.resize(w=120, h=10)


@pytest.mark.skipif(
sys.platform == "win32", reason="Commit unpaused containers doesn't work on Windows"
)
@pytest.mark.asyncio
async def test_commit(docker, image_name, shell_container):
shell_container.commit()
ret = await shell_container.commit()
img_id = ret["Id"]
img = await docker.images.inspect(img_id)
assert img["Container"].startswith(shell_container.id)
assert "Image" in img["ContainerConfig"]
assert image_name == img["ContainerConfig"]["Image"]
python_img = await docker.images.inspect(image_name)
python_id = python_img["Id"]
assert "Parent" in img
assert img["Parent"] == python_id
await docker.images.delete(img_id)


@pytest.mark.skipif(
sys.platform == "win32", reason="Commit unpaused containers doesn't work on Windows"
)
@pytest.mark.asyncio
async def test_commit_with_changes(docker, image_name, shell_container):
ret = await shell_container.commit(changes=["EXPOSE 8000", 'CMD ["py"]'])
img_id = ret["Id"]
img = await docker.images.inspect(img_id)
assert img["Container"].startswith(shell_container.id)
assert "8000/tcp" in img["Config"]["ExposedPorts"]
assert img["Config"]["Cmd"] == ["py"]
await docker.images.delete(img_id)


@pytest.mark.skipif(sys.platform == "win32", reason="Pause doesn't work on Windows")
@pytest.mark.asyncio
async def test_pause_unpause(shell_container):
await shell_container.pause()
container_info = await shell_container.show()
assert "State" in container_info
state = container_info["State"]
assert "ExitCode" in state
assert state["ExitCode"] == 0
assert "Running" in state
assert state["Running"] is True
assert "Paused" in state
assert state["Paused"] is True

await shell_container.unpause()
container_info = await shell_container.show()
assert "State" in container_info
state = container_info["State"]
assert "ExitCode" in state
assert state["ExitCode"] == 0
assert "Running" in state
assert state["Running"] is True
assert "Paused" in state
assert state["Paused"] is False