diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..d7f2776a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,11 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true +max_line_length = 80 + +[*.md] +trim_trailing_whitespace = false diff --git a/docker/api/container.py b/docker/api/container.py index 49c0b959..00fa1696 100644 --- a/docker/api/container.py +++ b/docker/api/container.py @@ -356,9 +356,14 @@ class ContainerApiMixin(object): @utils.minimum_version('1.17') @utils.check_resource - def stats(self, container, decode=None): + def stats(self, container, decode=None, stream=True): url = self._url("/containers/{0}/stats", container) - return self._stream_helper(self._get(url, stream=True), decode=decode) + if stream: + return self._stream_helper(self._get(url, stream=True), + decode=decode) + else: + return self._result(self._get(url, params={'stream': False}), + json=True) @utils.check_resource def stop(self, container, timeout=10): diff --git a/docs/api.md b/docs/api.md index a31aad02..68904276 100644 --- a/docs/api.md +++ b/docs/api.md @@ -874,6 +874,8 @@ This will stream statistics for a specific container. * container (str): The container to stream statistics for * decode (bool): If set to true, stream will be decoded into dicts on the fly. False by default. +* stream (bool): If set to false, only the current stats will be returned + instead of a stream. True by default. ```python >>> from docker import Client diff --git a/tests/integration/container_test.py b/tests/integration/container_test.py index 9bff6fcf..3ff40599 100644 --- a/tests/integration/container_test.py +++ b/tests/integration/container_test.py @@ -1040,3 +1040,34 @@ class PauseTest(api_test.BaseTestCase): self.assertEqual(state['Running'], True) self.assertIn('Paused', state) self.assertEqual(state['Paused'], False) + + +class GetContainerStatsTest(api_test.BaseTestCase): + @requires_api_version('1.19') + def test_get_container_stats_no_stream(self): + container = self.client.create_container( + BUSYBOX, ['sleep', '60'], + ) + self.tmp_containers.append(container) + self.client.start(container) + response = self.client.stats(container, stream=0) + self.client.kill(container) + + self.assertEqual(type(response), dict) + for key in ['read', 'network', 'precpu_stats', 'cpu_stats', + 'memory_stats', 'blkio_stats']: + self.assertIn(key, response) + + @requires_api_version('1.17') + def test_get_container_stats_stream(self): + container = self.client.create_container( + BUSYBOX, ['sleep', '60'], + ) + self.tmp_containers.append(container) + self.client.start(container) + stream = self.client.stats(container) + for chunk in stream: + self.assertEqual(type(chunk), dict) + for key in ['read', 'network', 'precpu_stats', 'cpu_stats', + 'memory_stats', 'blkio_stats']: + self.assertIn(key, chunk)