# Buggy code
async def demo(docker):
    try:
        await docker.images.get("alpine:latest")
    except DockerError as e:
        if e.status == 404:
            await docker.pull("alpine:latest")
        else:
            print("Error retrieving alpine:latest image.")
            return

    subscriber = docker.events.subscribe()

    config = {
        "Cmd": ["tail", "-f", "/var/log/dmesg"],
        "Image": "alpine:latest",
        "AttachStdin": False,
        "AttachStdout": True,
        "AttachStderr": True,
        "Tty": False,
        "OpenStdin": False,
        "StdinOnce": False,
    }
    container = await docker.containers.create_or_replace(config=config, name="testing")
    await container.start(config)
    print(f"=> created and started container {container._id[:12]}")

    while True:
        event = await subscriber.get()
        print(f"event: {event!r}")

        # Demonstrate simple event-driven container mgmt.
        if event["Actor"]["ID"] == container._id:
            if event["Action"] == "start":
                await container.stop()
                print(f"=> killed {container._id[:12]}")
            elif event["Action"] == "stop":
                await container.delete(force=True)
                print(f"=> deleted {container._id[:12]}")
            elif event["Action"] == "destroy":
                print("=> done with this container!")
                break


# Traceback (ConnectionRefusedError)
^CTraceback (most recent call last):
File "/tmp/events.py", line 24, in <module>
loop.run_until_complete(demo(docker))
File "/usr/lib/python3.6/asyncio/base_events.py", line 454, in run_until_complete
self.run_forever()
File "/usr/lib/python3.6/asyncio/base_events.py", line 421, in run_forever
self._run_once()
File "/usr/lib/python3.6/asyncio/base_events.py", line 1389, in _run_once
event_list = self._selector.select(timeout)
File "/usr/lib/python3.6/selectors.py", line 445, in select
fd_event_list = self._epoll.poll(timeout, max_ev)
KeyboardInterrupt
Task exception was never retrieved
future: <Task finished coro=<DockerEvents.run() done, defined at /home/cecile/.local/lib/python3.6/site-packages/aiodocker-0.7-py3.6.egg/aiodocker/docker.py:512> exception=ClientConnectorError(111, "Cannot connect to host 127.0.0.1:666 ssl:False [Can not connect to 127.0.0.1:666 [Connect call failed ('127.0.0.1', 666)]]")>
Traceback (most recent call last):
File "/home/cecile/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 651, in _create_direct_connection
local_addr=self._local_addr)
File "/usr/lib/python3.6/asyncio/base_events.py", line 776, in create_connection
raise exceptions[0]
File "/usr/lib/python3.6/asyncio/base_events.py", line 763, in create_connection
yield from self.sock_connect(sock, address)
File "/usr/lib/python3.6/asyncio/selector_events.py", line 451, in sock_connect
return (yield from fut)
File "/usr/lib/python3.6/asyncio/selector_events.py", line 481, in _sock_connect_cb
raise OSError(err, 'Connect call failed %s' % (address,))
ConnectionRefusedError: [Errno 111] Connect call failed ('127.0.0.1', 666)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/cecile/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 374, in connect
proto = yield from self._create_connection(req)
File "/home/cecile/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 628, in _create_connection
_, proto = yield from self._create_direct_connection(req)
File "/home/cecile/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 678, in _create_direct_connection
(req.host, req.port, exc.strerror)) from exc
aiohttp.client_exceptions.ClientConnectorError: [Errno 111] Can not connect to 127.0.0.1:666 [Connect call failed ('127.0.0.1', 666)]

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/cecile/.local/lib/python3.6/site-packages/aiodocker-0.7-py3.6.egg/aiodocker/docker.py", line 525, in run
params=params,
File "/home/cecile/.local/lib/python3.6/site-packages/aiodocker-0.7-py3.6.egg/aiodocker/docker.py", line 121, in _query
data=data, **kwargs)
File "/home/cecile/.local/lib/python3.6/site-packages/aiohttp/client.py", line 621, in __await__
resp = yield from self._coro
File "/home/cecile/.local/lib/python3.6/site-packages/aiohttp/client.py", line 225, in _request
conn = yield from self._connector.connect(req)
File "/home/cecile/.local/lib/python3.6/site-packages/aiohttp/connector.py", line 379, in connect
.format(key, exc.strerror)) from exc
aiohttp.client_exceptions.ClientConnectorError: [Errno 111] Cannot connect to host 127.0.0.1:666 ssl:False [Can not connect to 127.0.0.1:666 [Connect call failed ('127.0.0.1', 666)]]
Exception ignored in: <coroutine object demo at 0x7f9912428f68>
Traceback (most recent call last):
File "/tmp/events.py", line 13, in demo
File "/home/cecile/.local/lib/python3.6/site-packages/aiodocker-0.7-py3.6.egg/aiodocker/channel.py", line 14, in get
File "/usr/lib/python3.6/asyncio/queues.py", line 169, in get
File "/usr/lib/python3.6/asyncio/base_events.py", line 573, in call_soon
File "/usr/lib/python3.6/asyncio/base_events.py", line 357, in _check_closed
RuntimeError: Event loop is closed

# Fixed code
async def demo(docker):
    try:
        await docker.images.get("alpine:latest")
    except DockerError as e:
        if e.status == 404:
            await docker.pull("alpine:latest")
        else:
            print("Error retrieving alpine:latest image.")
            return

    subscriber = docker.events.subscribe()

    config = {
        "Cmd": ["tail", "-f", "/var/log/dmesg"],
        "Image": "alpine:latest",
        "AttachStdin": False,
        "AttachStdout": True,
        "AttachStderr": True,
        "Tty": False,
        "OpenStdin": False,
        "StdinOnce": False,
    }
    container = await docker.containers.create_or_replace(config=config, name="testing")
    await container.start(config)
    print(f"=> created and started container {container._id[:12]}")

    while True:
        event = await subscriber.get()
        if event is None:
            break
        print(f"event: {event!r}")

        # Demonstrate simple event-driven container mgmt.
        if event["Actor"]["ID"] == container._id:
            if event["Action"] == "start":
                await container.stop()
                print(f"=> killed {container._id[:12]}")
            elif event["Action"] == "stop":
                await container.delete(force=True)
                print(f"=> deleted {container._id[:12]}")
            elif event["Action"] == "destroy":
                print("=> done with this container!")
                break