diff --git a/docker/client.py b/docker/client.py index 563fe00a..ffc9c58f 100644 --- a/docker/client.py +++ b/docker/client.py @@ -966,11 +966,35 @@ class Client(requests.Session): res = self._post_json(url, data=start_config) self._raise_for_status(res) + def stats(self, container, aggregate=0): + if isinstance(container, dict): + container = container.get('Id') + url = self._url("/containers/{0}/stats".format(container)) + res = self._get(url, stream=True) + self._raise_for_status(res) + + stats_stream = res.iter_lines() + stats_array = [] + stats_aggregated = 0 + + if aggregate: + for stat_obj in stats_stream: + if stats_aggregated >= aggregate: + stats_aggregated = 0 + yield stats_array + stats_array = [] + stats_array.append(stat_obj) + stats_aggregated += 1 + else: + for stat_obj in stats_stream: + yield stat_obj + def stop(self, container, timeout=10): if isinstance(container, dict): container = container.get('Id') params = {'t': timeout} url = self._url("/containers/{0}/stop".format(container)) + res = self._post(url, params=params, timeout=(timeout + self.timeout)) self._raise_for_status(res) diff --git a/docs/api.md b/docs/api.md index 1d162e9f..4aac1a2a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -664,6 +664,32 @@ from. Optionally a single string joining container id's with commas None ``` +## stats + +The Docker API parallel to the `docker stats` command. +This will stream statistics for a specific container. + +`aggregate`, if 0 will return an iterable stream object of messages. +If aggregate is above 0, an iterable stream object of a list of messages in the size of `aggregate` will be returned. + +**Params**: + +* container (str): The container to start +* aggregate (int): The number of messages to aggregate before returning a stream object. + +```python +>>> from docker import Client +>>> aggregate = 10 +>>> cli = Client(base_url='tcp://127.0.0.1:2375') +>>> stats_obj = cli.stats('elasticsearch', aggregate=aggregate) +>>> for stat in stats: +>>> print(stat) +['{"read":"2015-02-11T21:47:30.49388286+02:00","network":{"rx_bytes":666052,"rx_packets":4409 ... +... +... +... +``` + ## stop Stops a container. Similar to the `docker stop` command. diff --git a/docs/change_log.md b/docs/change_log.md index d2e8cd7d..ccfa49b6 100644 --- a/docs/change_log.md +++ b/docs/change_log.md @@ -1,6 +1,14 @@ Change Log ========== +0.7.3 +----- + +### Features + +* Added support for `stats` API. + + 0.7.2 ----- diff --git a/tests/integration_test.py b/tests/integration_test.py index 46b630ec..41caf0b0 100644 --- a/tests/integration_test.py +++ b/tests/integration_test.py @@ -29,7 +29,7 @@ import six from test import Cleanup # FIXME: missing tests for -# export; history; import_image; insert; port; push; tag; get; load +# export; history; import_image; insert; port; push; tag; get; load; stats; DEFAULT_BASE_URL = os.environ.get('DOCKER_HOST')