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

Rewrite the docker_container_exec module #401

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
4 changes: 4 additions & 0 deletions changelogs/fragments/401-docker_container_exec-docker-api.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
major_changes:
- "docker_container_exec - no longer uses the Docker SDK for Python. It requires ``requests`` to be installed,
and depending on the features used has some more requirements. If the Docker SDK for Python is installed,
these requirements are likely met (https://github.com/ansible-collections/community.docker/pull/401)."
76 changes: 32 additions & 44 deletions plugins/modules/docker_container_exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,13 @@
version_added: 2.1.0

extends_documentation_fragment:
- community.docker.docker
- community.docker.docker.docker_py_1_documentation
- community.docker.docker.api_documentation
notes:
- Does not support C(check_mode).
author:
- "Felix Fontein (@felixfontein)"

requirements:
- "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 1.8.0"
- "Docker API >= 1.25"
'''

Expand Down Expand Up @@ -154,7 +152,7 @@
from ansible.module_utils.compat import selectors
from ansible.module_utils.six import string_types

from ansible_collections.community.docker.plugins.module_utils.common import (
from ansible_collections.community.docker.plugins.module_utils.common_api import (
AnsibleDockerClient,
RequestException,
)
Expand All @@ -168,11 +166,12 @@
DockerSocketHandlerModule,
)

try:
from docker.errors import DockerException, APIError, NotFound
except Exception:
# missing Docker SDK for Python handled in ansible.module_utils.docker.common
pass
from ansible_collections.community.docker.plugins.module_utils._api.errors import (
APIError,
DockerException,
NotFound,
)
from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import format_environment


def main():
Expand All @@ -191,8 +190,7 @@ def main():
)

option_minimal_versions = dict(
chdir=dict(docker_py_version='3.0.0', docker_api_version='1.35'),
env=dict(docker_py_version='2.3.0'),
chdir=dict(docker_api_version='1.35'),
)

client = AnsibleDockerClient(
Expand Down Expand Up @@ -231,34 +229,31 @@ def main():
stdin += '\n'

try:
kwargs = {}
if chdir is not None:
kwargs['workdir'] = chdir
if env is not None:
kwargs['environment'] = env
exec_data = client.exec_create(
container,
argv,
stdout=True,
stderr=True,
stdin=bool(stdin),
user=user or '',
**kwargs
)
data = {
'Container': container,
'User': user or '',
'Privileged': False,
'Tty': False,
'AttachStdin': bool(stdin),
'AttachStdout': True,
'AttachStderr': True,
'Cmd': argv,
'Env': format_environment(env) if env is not None else None,
}
exec_data = client.post_json_to_json('/containers/{0}/exec', container, data=data)
exec_id = exec_data['Id']

data = {
'Tty': tty,
'Detach': detach,
}
if detach:
client.exec_start(exec_id, tty=tty, detach=True)
client.post_json_to_text('/exec/{0}/start', exec_id, data=data)
client.module.exit_json(changed=True, exec_id=exec_id)

else:
if stdin and not detach:
exec_socket = client.exec_start(
exec_id,
tty=tty,
detach=False,
socket=True,
)
exec_socket = client.post_json_to_stream_socket('/exec/{0}/start', exec_id, data=data)
try:
with DockerSocketHandlerModule(exec_socket, client.module, selectors) as exec_socket_handler:
if stdin:
Expand All @@ -268,16 +263,9 @@ def main():
finally:
exec_socket.close()
else:
stdout, stderr = client.exec_start(
exec_id,
tty=tty,
detach=False,
stream=False,
socket=False,
demux=True,
)
stdout, stderr = client.post_json_to_stream('/exec/{0}/start', exec_id, data=data, stream=False, tty=tty, demux=True)

result = client.exec_inspect(exec_id)
result = client.get_json('/exec/{0}/json', exec_id)

stdout = to_text(stdout or b'')
stderr = to_text(stderr or b'')
Expand All @@ -296,12 +284,12 @@ def main():
except APIError as e:
if e.response and e.response.status_code == 409:
client.fail('The container "{0}" has been paused ({1})'.format(container, to_native(e)))
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
except DockerException as e:
client.fail('An unexpected docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
client.fail('An unexpected Docker error occurred: {0}'.format(to_native(e)), exception=traceback.format_exc())
except RequestException as e:
client.fail(
'An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {0}'.format(to_native(e)),
'An unexpected requests error occurred when trying to talk to the Docker daemon: {0}'.format(to_native(e)),
exception=traceback.format_exc())


Expand Down
46 changes: 22 additions & 24 deletions tests/integration/targets/docker_container_exec/tasks/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -190,28 +190,26 @@
- "'stderr' not in result"
- result.exec_id is string

- when: docker_py_version is version('2.3.0', '>=')
block:
- name: Execute in a present container (environment variable)
docker_container_exec:
container: "{{ cname }}"
argv:
- /bin/sh
- '-c'
- 'echo "$FOO" ; echo $FOO > /dev/stderr'
env:
FOO: |-
bar
baz
register: result

- assert:
that:
- result.rc == 0
- result.stdout == 'bar\nbaz'
- result.stdout_lines == ['bar', 'baz']
- result.stderr == 'bar baz'
- result.stderr_lines == ['bar baz']
- name: Execute in a present container (environment variable)
docker_container_exec:
container: "{{ cname }}"
argv:
- /bin/sh
- '-c'
- 'echo "$FOO" ; echo $FOO > /dev/stderr'
env:
FOO: |-
bar
baz
register: result

- assert:
that:
- result.rc == 0
- result.stdout == 'bar\nbaz'
- result.stdout_lines == ['bar', 'baz']
- result.stderr == 'bar baz'
- result.stderr_lines == ['bar baz']

always:
- name: Cleanup
Expand All @@ -220,7 +218,7 @@
state: absent
force_kill: yes

when: docker_py_version is version('1.8.0', '>=') and docker_api_version is version('1.25', '>=')
when: docker_api_version is version('1.25', '>=')

- fail: msg="Too old docker / docker-py version to run docker_container_exec tests!"
when: not(docker_py_version is version('1.8.0', '>=') and docker_api_version is version('1.25', '>=')) and (ansible_distribution != 'CentOS' or ansible_distribution_major_version|int > 6)
when: not(docker_api_version is version('1.25', '>=')) and (ansible_distribution != 'CentOS' or ansible_distribution_major_version|int > 6)