Skip to content

Commit

Permalink
Add docker-compose event
Browse files Browse the repository at this point in the history
Signed-off-by: Daniel Nephin <dnephin@docker.com>
  • Loading branch information
dnephin committed Nov 21, 2015
1 parent 1c58098 commit 1cc24f1
Show file tree
Hide file tree
Showing 7 changed files with 138 additions and 3 deletions.
16 changes: 14 additions & 2 deletions compose/cli/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import print_function
from __future__ import unicode_literals

import json
import logging
import re
import signal
Expand Down Expand Up @@ -53,7 +54,7 @@ def main():
command = TopLevelCommand()
command.sys_dispatch()
except KeyboardInterrupt:
log.error("\nAborting.")
log.warn("Aborting.")
sys.exit(1)
except (UserError, NoSuchService, ConfigurationError, legacy.LegacyError) as e:
log.error(e.msg)
Expand Down Expand Up @@ -199,8 +200,19 @@ def events(self, project, options):
Usage: events [options] [SERVICE...]
Options:
--json
--json Output events as a stream of json objects
"""
def format_event(event):
return ("{time}: service={service} event={event} "
"container={container} image={image}").format(**event)

def json_format_event(event):
event['time'] = event['time'].isoformat()
return json.dumps(event)

for event in project.events():
formatter = json_format_event if options['--json'] else format_event
print(formatter(event))

def help(self, project, options):
"""
Expand Down
1 change: 1 addition & 0 deletions compose/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

DEFAULT_TIMEOUT = 10
HTTP_TIMEOUT = int(os.environ.get('COMPOSE_HTTP_TIMEOUT', os.environ.get('DOCKER_CLIENT_TIMEOUT', 60)))
IMAGE_EVENTS = ['delete', 'import', 'pull', 'push', 'tag', 'untag']
IS_WINDOWS_PLATFORM = (sys.platform == "win32")
LABEL_CONTAINER_NUMBER = 'com.docker.compose.container-number'
LABEL_ONE_OFF = 'com.docker.compose.oneoff'
Expand Down
32 changes: 32 additions & 0 deletions compose/project.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import absolute_import
from __future__ import unicode_literals

import datetime
import logging
from functools import reduce

Expand All @@ -10,6 +11,7 @@
from .config import ConfigurationError
from .config import get_service_name_from_net
from .const import DEFAULT_TIMEOUT
from .const import IMAGE_EVENTS
from .const import LABEL_ONE_OFF
from .const import LABEL_PROJECT
from .const import LABEL_SERVICE
Expand All @@ -22,6 +24,7 @@
from .service import Service
from .service import ServiceNet
from .service import VolumeFromSpec
from .utils import microseconds_from_time_nano
from .utils import parallel_execute


Expand Down Expand Up @@ -285,6 +288,35 @@ def build(self, service_names=None, no_cache=False, pull=False, force_rm=False):
else:
log.info('%s uses an image, skipping' % service.name)

def events(self):
def build_container_event(event, container):
time = datetime.datetime.fromtimestamp(event['time'])
time = time.replace(
microsecond=microseconds_from_time_nano(event['timeNano']))
return {
'service': container.service,
'event': event['status'],
'container': container.id,
'image': event['from'],
'time': time,
}

service_names = set(self.service_names)
for event in self.client.events(
filters={'label': self.labels()},
decode=True
):
if event['status'] in IMAGE_EVENTS:
# We don't receive any image events because labels aren't applied
# to images
continue

# TODO: cache this
container = Container.from_id(self.client, event['id'])
if container.service not in service_names:
continue
yield build_container_event(event, container)

def up(self,
service_names=None,
start_deps=True,
Expand Down
4 changes: 4 additions & 0 deletions compose/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,7 @@ def json_hash(obj):
h = hashlib.sha256()
h.update(dump.encode('utf8'))
return h.hexdigest()


def microseconds_from_time_nano(time_nano):
return int(time_nano % 1000000000 / 1000)
1 change: 0 additions & 1 deletion docs/reference/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,3 @@ The following pages describe the usage information for the [docker-compose](dock

* [CLI environment variables](overview.md)
* [docker-compose Command](docker-compose.md)

11 changes: 11 additions & 0 deletions tests/acceptance/cli_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import absolute_import

import json
import os
import shlex
import signal
Expand Down Expand Up @@ -758,6 +759,16 @@ def get_port(number, index=None):
self.assertEqual(get_port(3000, index=2), containers[1].get_local_port(3000))
self.assertEqual(get_port(3002), "")

def test_events_json(self):
events_proc = start_process(self.base_dir, ['events', '--json'])
self.dispatch(['up', '-d'])
wait_on_condition(ContainerCountCondition(self.project, 2))

os.kill(events_proc.pid, signal.SIGINT)
result = wait_on_process(events_proc, returncode=1)
lines = [json.loads(line) for line in result.stdout.rstrip().split('\n')]
assert [e['event'] for e in lines] == ['create', 'start', 'create', 'start']

def test_env_file_relative_to_compose_file(self):
config_path = os.path.abspath('tests/fixtures/env-file/docker-compose.yml')
self.dispatch(['-f', config_path, 'up', '-d'], None)
Expand Down
76 changes: 76 additions & 0 deletions tests/unit/project_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import unicode_literals

import datetime

import docker

from .. import mock
Expand Down Expand Up @@ -215,6 +217,80 @@ def test_use_volumes_from_service_container(self, mock_return):
], None)
self.assertEqual(project.get_service('test')._get_volumes_from(), [container_ids[0] + ':rw'])

def test_events(self):
services = [Service(name='web'), Service(name='db')]
project = Project('test', services, self.mock_client)
self.mock_client.events.return_value = iter([
{
'status': 'create',
'from': 'example/image',
'id': 'abcde',
'time': 1420092061,
'timeNano': 14200920610000002000,
},
{
'status': 'attach',
'from': 'example/image',
'id': 'abcde',
'time': 1420092061,
'timeNano': 14200920610000003000,
},
{
'status': 'create',
'from': 'example/other',
'id': 'bdbdbd',
'time': 1420092061,
'timeNano': 14200920610000005000,
},
{
'status': 'create',
'from': 'example/db',
'id': 'ababa',
'time': 1420092061,
'timeNano': 14200920610000004000,
},
])

def get_container(cid):
if cid == 'abcde':
labels = {LABEL_SERVICE: 'web'}
elif cid == 'ababa':
labels = {LABEL_SERVICE: 'db'}
else:
labels = {}
return {'Id': cid, 'Config': {'Labels': labels}}

self.mock_client.inspect_container.side_effect = get_container

events = project.events()

events_list = list(events)
# Assert the return value is a generator
assert not list(events)
assert events_list == [
{
'service': 'web',
'event': 'create',
'container': 'abcde',
'image': 'example/image',
'time': datetime.datetime(2015, 1, 1, 1, 1, 1, 2),
},
{
'service': 'web',
'event': 'attach',
'container': 'abcde',
'image': 'example/image',
'time': datetime.datetime(2015, 1, 1, 1, 1, 1, 3),
},
{
'service': 'db',
'event': 'create',
'container': 'ababa',
'image': 'example/db',
'time': datetime.datetime(2015, 1, 1, 1, 1, 1, 4),
},
]

def test_net_unset(self):
project = Project.from_dicts('test', [
{
Expand Down

0 comments on commit 1cc24f1

Please sign in to comment.