anon-iclr-submission/benchname-bug-localization huggingface dataset:
Repository: docker/docker-py
Issue: tlsv1 alert protocol version on 1.7.1 and 1.7.2 but not on 1.7.0

Similar to #949 I'm discovering issues with latest versions of `docker-py` running against docker 1.10.2 instance. I'm using `docker.utils.kwargs_from_env(assert_hostname=False)`. Things work fine with version 1.7.0.

Docker client is initialized via

```
client = docker.Client(
    version='auto',
    **docker.utils.kwargs_from_env(assert_hostname=False))
```

with docker environment variables being set to the following (via docker-machine)

```
DOCKER_HOST=tcp://192.168.156.137:2376
DOCKER_MACHINE_NAME=dev2
DOCKER_TLS_VERIFY=1
DOCKER_CERT_PATH=/Users/benjixx/.docker/machine/machines/dev2
```

docker-py 1.7.1 and 1.7.2 now raise the following exception:

```
DockerException: Error while fetching server API version: [Errno 1] _ssl.c:507: error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
```

Any idea what's happening here?


Changed files:
docker/tls.py

diff --git a/docker/tls.py b/docker/tls.py
index 83b0ff7e..7abfa60e 100644
--- a/docker/tls.py
+++ b/docker/tls.py
@@ -1,4 +1,5 @@
 import os
+import ssl
 
 from . import errors
 from .ssladapter import ssladapter
@@ -19,10 +20,14 @@ class TLSConfig(object):
         # here, but also disable any public/default CA pool verification by
         # leaving tls_verify=False
 
-        self.ssl_version = ssl_version
         self.assert_hostname = assert_hostname
         self.assert_fingerprint = assert_fingerprint
 
+        # TLS v1.0 seems to be the safest default; SSLv23 fails in mysterious
+        # ways: https://github.com/docker/docker-py/issues/963
+
+        self.ssl_version = ssl_version or ssl.PROTOCOL_TLSv1
+
         # "tls" and "tls_verify" must have both or neither cert/key files
         # In either case, Alert the user when both are expected, but any are
         # missing.
Repository: docker/docker-py
Issue: DockerClient.secrets is not a property

`DockerClient.secrets` is not decorated with `property` and so must be called rather than just accessed. This is inconsistent with the docs and similar collections on the client attribute (e.g. images, containers, etc.).

Changed files:
docker/client.py

diff --git a/docker/client.py b/docker/client.py
index 09abd633..66ef60f3 100644
--- a/docker/client.py
+++ b/docker/client.py
@@ -119,6 +119,7 @@ class DockerClient(object):
         """
         return PluginCollection(client=self)
 
+    @property
     def secrets(self):
         """
         An object for managing secrets on the server. See the
Repository: docker/docker-py
Issue: attach is causing an "Invalid Argument" exception from os.read

``` python
stream = client.attach(container, stream=True, stdout=True, stderr=True)
for chunk in stream:
    pass
```

Results in:

```
  File "/Users/michael/work/oss/marina/marina/build.py", line 695, in watcher
    for chunk in stream:
  File ".venv/lib/python3.5/site-packages/docker/utils/socket.py", line 67, in frames_iter
    yield read(socket, n)
  File ".venv/lib/python3.5/site-packages/docker/utils/socket.py", line 25, in read
    return os.read(socket.fileno(), n)
OSError: [Errno 22] Invalid argument
```

Using docker-py 1.10.2 on OS X 10.11.6 with docker for mac 1.12.0-rc3. Reverting to 1.9.0 fixes the issue.


Changed files:
docker/utils/socket.py

diff --git a/docker/utils/socket.py b/docker/utils/socket.py
index 164b845a..4080f253 100644
--- a/docker/utils/socket.py
+++ b/docker/utils/socket.py
@@ -69,7 +69,11 @@ def frames_iter(socket):
     """
     Returns a generator of frames read from socket
     """
-    n = next_frame_size(socket)
-    while n > 0:
-        yield read(socket, n)
+    while True:
         n = next_frame_size(socket)
+        if n == 0:
+            break
+        while n > 0:
+            result = read(socket, n)
+            n -= len(result)
+            yield result
Repository: docker/docker-py
Issue: Issue with port option in 2.4.0 version

Hi,
I update to the 2.4 today and i got issue with docker-compose when i try to add the following line to my configuration file (docker-compose.yml) : 
`ports:
            - "127.0.0.1:9292:9090"`

I got the following error:

`
ERROR: for ContainerName  expected string or buffer
Traceback (most recent call last):
  File "/usr/local/bin/docker-compose", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/compose/cli/main.py", line 68, in main
    command()
  File "/usr/local/lib/python2.7/dist-packages/compose/cli/main.py", line 118, in perform_command
    handler(command, command_options)
  File "/usr/local/lib/python2.7/dist-packages/compose/cli/main.py", line 926, in up
    scale_override=parse_scale_args(options['--scale']),
  File "/usr/local/lib/python2.7/dist-packages/compose/project.py", line 424, in up
    get_deps
  File "/usr/local/lib/python2.7/dist-packages/compose/parallel.py", line 69, in parallel_execute
    raise error_to_reraise
TypeError: expected string or buffer
`

I have no issue when i downgrade again to the 2.3 version of the package

To reproduce the issue, i use the following configuration ( it doesn't seem to depend on the image):
```
version: '2'

services :
    ContainerName:
        image: bae2d441e03a
        ports:
            - "127.0.0.1:9292:9090"
```

I run on Ubuntu 14.04.5 LTS with the following package:
```
docker==2.4.0
docker-compose==1.14.0
docker-pycreds==0.2.1
dockerpty==0.4.1
Python 2.7.6
Client:
 Version:      17.05.0-ce
 API version:  1.29
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:06:06 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.05.0-ce
 API version:  1.29 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:06:06 2017
 OS/Arch:      linux/amd64
 Experimental: false
```

Changed files:
docker/utils/ports.py

diff --git a/docker/utils/ports.py b/docker/utils/ports.py
index 8f713c72..bf7d6972 100644
--- a/docker/utils/ports.py
+++ b/docker/utils/ports.py
@@ -54,6 +54,11 @@ def port_range(start, end, proto, randomly_available_port=False):
 
 
 def split_port(port):
+    if hasattr(port, 'legacy_repr'):
+        # This is the worst hack, but it prevents a bug in Compose 1.14.0
+        # https://github.com/docker/docker-py/issues/1668
+        # TODO: remove once fixed in Compose stable
+        port = port.legacy_repr()
     port = str(port)
     match = PORT_SPEC.match(port)
     if match is None:
Repository: docker/docker-py
Issue: Probably invalid version checking in container creation

Hi.
I've stumbled upon something i think is a not up-to-date code.

utils.py at line 794 in my distribution (1.6.0) states following:

```
if compare_version('1.10', version) >= 0:
    message = ('{0!r} parameter has no effect on create_container().'
               ' It has been moved to start()')
    if dns is not None:
        raise errors.InvalidVersion(message.format('dns'))
    if volumes_from is not None:
        raise errors.InvalidVersion(message.format('volumes_from'))
```

As far as i can read from docs, this is not true - both Dns and VolumesFrom are seen in HostConfig for API 1.21. Even if everything is okay with this code, there is still a problem i'm struggling to solve - some of the HostConfig options can be specified in `.container_create()`, but not on `.start()`, e.g. logging driver and options may be set only during creation, but if i need to use custom DNS, i have to specify it on `.start()` call, and this will override whole HostConfig, erasing my logging configuration. Since this code directly raise exceptions, i have no option but to create whole dict directly and pass it to `container_from_configuration()`.

I'm sorry i'm not doing direct pull request instead of issue, but i don't have enough time to figure out correct version constraints and get into projects conventions - sadly, i'm no pythonist and can't do it.


Changed files:
docker/utils/utils.py

diff --git a/docker/utils/utils.py b/docker/utils/utils.py
index dc46f1ef..07d57d12 100644
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -889,7 +889,7 @@ def create_container_config(
 
     if compare_version('1.10', version) >= 0:
         message = ('{0!r} parameter has no effect on create_container().'
-                   ' It has been moved to start()')
+                   ' It has been moved to host_config')
         if dns is not None:
             raise errors.InvalidVersion(message.format('dns'))
         if volumes_from is not None:
Repository: docker/docker-py
Issue: Issue with port option in 2.4.0 version

Hi,
I update to the 2.4 today and i got issue with docker-compose when i try to add the following line to my configuration file (docker-compose.yml) : 
`ports:
            - "127.0.0.1:9292:9090"`

I got the following error:

`
ERROR: for ContainerName  expected string or buffer
Traceback (most recent call last):
  File "/usr/local/bin/docker-compose", line 11, in <module>
    sys.exit(main())
  File "/usr/local/lib/python2.7/dist-packages/compose/cli/main.py", line 68, in main
    command()
  File "/usr/local/lib/python2.7/dist-packages/compose/cli/main.py", line 118, in perform_command
    handler(command, command_options)
  File "/usr/local/lib/python2.7/dist-packages/compose/cli/main.py", line 926, in up
    scale_override=parse_scale_args(options['--scale']),
  File "/usr/local/lib/python2.7/dist-packages/compose/project.py", line 424, in up
    get_deps
  File "/usr/local/lib/python2.7/dist-packages/compose/parallel.py", line 69, in parallel_execute
    raise error_to_reraise
TypeError: expected string or buffer
`

I have no issue when i downgrade again to the 2.3 version of the package

To reproduce the issue, i use the following configuration ( it doesn't seem to depend on the image):
```
version: '2'

services :
    ContainerName:
        image: bae2d441e03a
        ports:
            - "127.0.0.1:9292:9090"
```

I run on Ubuntu 14.04.5 LTS with the following package:
```
docker==2.4.0
docker-compose==1.14.0
docker-pycreds==0.2.1
dockerpty==0.4.1
Python 2.7.6
Client:
 Version:      17.05.0-ce
 API version:  1.29
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:06:06 2017
 OS/Arch:      linux/amd64

Server:
 Version:      17.05.0-ce
 API version:  1.29 (minimum version 1.12)
 Go version:   go1.7.5
 Git commit:   89658be
 Built:        Thu May  4 22:06:06 2017
 OS/Arch:      linux/amd64
 Experimental: false
```

Changed files:
tests/unit/utils_test.py, docker/utils/ports.py

diff --git a/docker/utils/ports.py b/docker/utils/ports.py
index 57332dee..8f713c72 100644
--- a/docker/utils/ports.py
+++ b/docker/utils/ports.py
@@ -54,6 +54,7 @@ def port_range(start, end, proto, randomly_available_port=False):
 
 
 def split_port(port):
+    port = str(port)
     match = PORT_SPEC.match(port)
     if match is None:
         _raise_invalid_port(port)
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py
index c25881d1..a2d463d7 100644
--- a/tests/unit/utils_test.py
+++ b/tests/unit/utils_test.py
@@ -587,6 +587,9 @@ class PortsTest(unittest.TestCase):
     def test_split_port_empty_string(self):
         self.assertRaises(ValueError, lambda: split_port(""))
 
+    def test_split_port_non_string(self):
+        assert split_port(1243) == (['1243'], None)
+
     def test_build_port_bindings_with_one_port(self):
         port_bindings = build_port_bindings(["127.0.0.1:1000:1000"])
         self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")])
Repository: docker/docker-py
Issue: Support environment variables without values

See https://github.com/docker/compose/pull/2997 for some context.

docker-py assumes that all variables should have an `=` but the docker-cli passes environment variables without values as just the key, which is super weird, but apparently swarm is relying on that currently.


Changed files:
tests/integration/container_test.py, docker/utils/utils.py

diff --git a/docker/utils/utils.py b/docker/utils/utils.py
index 6fcf037a..bde18b6b 100644
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -821,6 +821,14 @@ def split_command(command):
     return shlex.split(command)
 
 
+def format_environment(environment):
+    def format_env(key, value):
+        if not value:
+            return key
+        return '{key}={value}'.format(key=key, value=value)
+    return [format_env(*var) for var in six.iteritems(environment)]
+
+
 def create_container_config(
     version, image, command, hostname=None, user=None, detach=False,
     stdin_open=False, tty=False, mem_limit=None, ports=None, environment=None,
@@ -836,10 +844,7 @@ def create_container_config(
         entrypoint = split_command(entrypoint)
 
     if isinstance(environment, dict):
-        environment = [
-            six.text_type('{0}={1}').format(k, v)
-            for k, v in six.iteritems(environment)
-        ]
+        environment = format_environment(environment)
 
     if labels is not None and compare_version('1.18', version) < 0:
         raise errors.InvalidVersion(
diff --git a/tests/integration/container_test.py b/tests/integration/container_test.py
index 1714599b..eb5b7467 100644
--- a/tests/integration/container_test.py
+++ b/tests/integration/container_test.py
@@ -370,6 +370,16 @@ class CreateContainerTest(helpers.BaseTestCase):
         self.assertRaises(ValueError,
                           self.client.create_host_config, pid_mode='40')
 
+    def test_create_with_environment_variable_no_value(self):
+        container = self.client.create_container(
+            BUSYBOX,
+            ['echo'],
+            environment={'Foo': None, 'Other': 'one'},
+        )
+        self.tmp_containers.append(container['Id'])
+        config = self.client.inspect_container(container['Id'])
+        assert sorted(config['Config']['Env']) == sorted(['Foo', 'Other=one'])
+
 
 class VolumeBindTest(helpers.BaseTestCase):
     def setUp(self):
Repository: docker/docker-py
Issue: login failed with default registry

I am using docker-py (1.8.0) and trying to using login API.

If I don't input `registry='https://index.docker.io/v1/'` .
It will raise exception as following:

```
docker.errors.APIError: 500 Server Error: Internal Server Error ("Unexpected status code [301] :")
```

But I saw https://github.com/docker/docker-py/blob/81edb398ebf7ce5c7ef14aa0739de5329589aabe/docker/api/daemon.py#L52 in source code. Should work with default registry.


Changed files:
docker/api/daemon.py

diff --git a/docker/api/daemon.py b/docker/api/daemon.py
index a149e5e3..9ebe73c0 100644
--- a/docker/api/daemon.py
+++ b/docker/api/daemon.py
@@ -49,8 +49,6 @@ class DaemonApiMixin(object):
         elif not self._auth_configs:
             self._auth_configs = auth.load_config()
 
-        registry = registry or auth.INDEX_URL
-
         authcfg = auth.resolve_authconfig(self._auth_configs, registry)
         # If we found an existing auth config for this registry and username
         # combination, we can return it immediately unless reauth is requested.
@@ -67,7 +65,7 @@ class DaemonApiMixin(object):
 
         response = self._post_json(self._url('/auth'), data=req_data)
         if response.status_code == 200:
-            self._auth_configs[registry] = req_data
+            self._auth_configs[registry or auth.INDEX_NAME] = req_data
         return self._result(response, json=True)
 
     def ping(self):
Repository: docker/docker-py
Issue: NpipeSocket.makefile crashes when bufsize < 0

**Original report**: https://github.com/docker/compose/issues/3901#issuecomment-244828701

Negative `bufsize` should be handled.


Changed files:
docker/transport/npipesocket.py

diff --git a/docker/transport/npipesocket.py b/docker/transport/npipesocket.py
index 35418ef1..9010cebe 100644
--- a/docker/transport/npipesocket.py
+++ b/docker/transport/npipesocket.py
@@ -94,7 +94,7 @@ class NpipeSocket(object):
         if mode.strip('b') != 'r':
             raise NotImplementedError()
         rawio = NpipeFileIOBase(self)
-        if bufsize is None:
+        if bufsize is None or bufsize < 0:
             bufsize = io.DEFAULT_BUFFER_SIZE
         return io.BufferedReader(rawio, buffer_size=bufsize)
Repository: docker/docker-py
Issue: NpipeSocket.settimeout - Blocking and non-blocking are mixed up

`settimeout(None)` puts the socket in non-blocking mode, `settimeout(0)` in blocking mode. Specification indicates it should be the other way around.

Changed files:
docker/transport/npipesocket.py

diff --git a/docker/transport/npipesocket.py b/docker/transport/npipesocket.py
index 509cabfb..c04b39dd 100644
--- a/docker/transport/npipesocket.py
+++ b/docker/transport/npipesocket.py
@@ -170,13 +170,16 @@ class NpipeSocket(object):
 
     def settimeout(self, value):
         if value is None:
-            self._timeout = win32pipe.NMPWAIT_NOWAIT
+            # Blocking mode
+            self._timeout = win32pipe.NMPWAIT_WAIT_FOREVER
         elif not isinstance(value, (float, int)) or value < 0:
             raise ValueError('Timeout value out of range')
         elif value == 0:
-            self._timeout = win32pipe.NMPWAIT_USE_DEFAULT_WAIT
+            # Non-blocking mode
+            self._timeout = win32pipe.NMPWAIT_NO_WAIT
         else:
-            self._timeout = value
+            # Timeout mode - Value converted to milliseconds
+            self._timeout = value * 1000
 
     def gettimeout(self):
         return self._timeout
Repository: docker/docker-py
Issue: Exception retrieving untagged images on api >= 1.24

Docker API >= 1.24 will return a null object if image tags DNE instead of not including it in the response. This makes the dict.get fail to catch the null case and the list comprehension to iterate over a non-iterable.

```
  File "<stdin>", line 1, in <module>
  File "docker/models/images.py", line 16, in __repr__
    return "<%s: '%s'>" % (self.__class__.__name__, "', '".join(self.tags))
  File "docker/models/images.py", line 34, in tags
    tag for tag in self.attrs.get('RepoTags', [])
TypeError: 'NoneType' object is not iterable
```

This is similar to an issue seen in [salt](https://github.com/saltstack/salt/pull/35447/commits/b833b5f9587534d3b843a026ef91abc4ec929d0f)

Was able to get things working with a pretty quick change:
```
diff --git a/docker/models/images.py b/docker/models/images.py
index 32068e6..39a640d 100644
--- a/docker/models/images.py
+++ b/docker/models/images.py
@@ -30,9 +30,11 @@ class Image(Model):
         """
         The image's tags.
         """
+        tags = self.attrs.get('RepoTags', [])
+        if tags is None:
+            return []
         return [
-            tag for tag in self.attrs.get('RepoTags', [])
-            if tag != '<none>:<none>'
+            tag for tag in tags if tag != '<none>:<none>'
         ]
 
     def history(self):
```

Changed files:
tests/unit/models_images_test.py, docker/models/images.py

diff --git a/docker/models/images.py b/docker/models/images.py
index 32068e69..6f8f4fe2 100644
--- a/docker/models/images.py
+++ b/docker/models/images.py
@@ -30,10 +30,10 @@ class Image(Model):
         """
         The image's tags.
         """
-        return [
-            tag for tag in self.attrs.get('RepoTags', [])
-            if tag != '<none>:<none>'
-        ]
+        tags = self.attrs.get('RepoTags')
+        if tags is None:
+            tags = []
+        return [tag for tag in tags if tag != '<none>:<none>']
 
     def history(self):
         """
diff --git a/tests/unit/models_images_test.py b/tests/unit/models_images_test.py
index 392c58d7..efb21166 100644
--- a/tests/unit/models_images_test.py
+++ b/tests/unit/models_images_test.py
@@ -83,6 +83,11 @@ class ImageTest(unittest.TestCase):
         })
         assert image.tags == []
 
+        image = Image(attrs={
+            'RepoTags': None
+        })
+        assert image.tags == []
+
     def test_history(self):
         client = make_fake_client()
         image = client.images.get(FAKE_IMAGE_ID)
Repository: docker/docker-py
Issue: image.tag does not return anything

There's no return statement in `images.tag`:
https://github.com/docker/docker-py/blob/master/docker/models/images.py#L99

[Readthedocs](https://docker-py.readthedocs.io/en/stable/images.html) (and the method comments) suggest it should return a bool for success.

I saw this running version 2.2.1 of the library
```
# pip freeze | grep docker
docker==2.2.1
docker-pycreds==0.2.1
```

**Repro code:**
```
import docker
def test_tag(id):
    client = docker.DockerClient()
    image = client.images.get(id)
    tag_result = image.tag('test_image', tag='test_tag')
    if tag_result is None:
        print('oops')
```

Changed files:
tests/integration/models_images_test.py, docker/models/images.py

diff --git a/docker/models/images.py b/docker/models/images.py
index a9ed65ee..e8af101d 100644
--- a/docker/models/images.py
+++ b/docker/models/images.py
@@ -96,7 +96,7 @@ class Image(Model):
         Returns:
             (bool): ``True`` if successful
         """
-        self.client.api.tag(self.id, repository, tag=tag, **kwargs)
+        return self.client.api.tag(self.id, repository, tag=tag, **kwargs)
 
 
 class ImageCollection(Collection):
diff --git a/tests/integration/models_images_test.py b/tests/integration/models_images_test.py
index 6d61e497..881df0a1 100644
--- a/tests/integration/models_images_test.py
+++ b/tests/integration/models_images_test.py
@@ -71,7 +71,8 @@ class ImageTest(BaseIntegrationTest):
         client = docker.from_env(version=TEST_API_VERSION)
         image = client.images.pull('alpine:latest')
 
-        image.tag(repo, tag)
+        result = image.tag(repo, tag)
+        assert result is True
         self.tmp_imgs.append(identifier)
         assert image.id in get_ids(client.images.list(repo))
         assert image.id in get_ids(client.images.list(identifier))
Repository: docker/docker-py
Issue: Can't Create/Update an replicated service with replicas = 0, bug finded

I try to update a service with the following code:
```
 service.update(
            name=service.name,
            mode=docker.types.ServiceMode('replicated', replicas=0),
            networks=networks_list,
        )
```
First, I want to update the replicas only but I have to put name and network or the api think I want to change them (?) then send me an error.
Second, the ServiceMode object created here don't work and looks like this :  `{'replicated': {}}`
The reason for this is https://github.com/docker/docker-py/blob/master/docker/types/services.py#L410 where the if should be an if exist.
I would love to do a pull request but i'm a newbie and I'm already lost with my first one : #1568 
Thx for everything

Changed files:
tests/unit/dockertypes_test.py, docker/types/services.py

diff --git a/docker/types/services.py b/docker/types/services.py
index 9291c9bd..e7787ec8 100644
--- a/docker/types/services.py
+++ b/docker/types/services.py
@@ -407,7 +407,7 @@ class ServiceMode(dict):
                 'replicas can only be used for replicated mode'
             )
         self[mode] = {}
-        if replicas:
+        if replicas is not None:
             self[mode]['Replicas'] = replicas
 
     @property
diff --git a/tests/unit/dockertypes_test.py b/tests/unit/dockertypes_test.py
index cb1d90ca..160fabdd 100644
--- a/tests/unit/dockertypes_test.py
+++ b/tests/unit/dockertypes_test.py
@@ -305,6 +305,12 @@ class ServiceModeTest(unittest.TestCase):
         assert mode.mode == 'replicated'
         assert mode.replicas == 21
 
+    def test_replicated_replicas_0(self):
+        mode = ServiceMode('replicated', 0)
+        assert mode == {'replicated': {'Replicas': 0}}
+        assert mode.mode == 'replicated'
+        assert mode.replicas == 0
+
     def test_invalid_mode(self):
         with pytest.raises(InvalidArgument):
             ServiceMode('foobar')
Repository: docker/docker-py
Issue: .dockerignore file with space-only lines breaks build on Windows

Originally reported in https://github.com/docker/compose/issues/5526

Changed files:
tests/integration/api_build_test.py, docker/api/build.py

diff --git a/docker/api/build.py b/docker/api/build.py
index 9ff2dfb3..34456ab3 100644
--- a/docker/api/build.py
+++ b/docker/api/build.py
@@ -145,7 +145,9 @@ class BuildApiMixin(object):
             exclude = None
             if os.path.exists(dockerignore):
                 with open(dockerignore, 'r') as f:
-                    exclude = list(filter(bool, f.read().splitlines()))
+                    exclude = list(filter(
+                        bool, [l.strip() for l in f.read().splitlines()]
+                    ))
             context = utils.tar(
                 path, exclude=exclude, dockerfile=dockerfile, gzip=gzip
             )
diff --git a/tests/integration/api_build_test.py b/tests/integration/api_build_test.py
index 8e98cc9f..7cc32346 100644
--- a/tests/integration/api_build_test.py
+++ b/tests/integration/api_build_test.py
@@ -352,6 +352,28 @@ class BuildTest(BaseAPIIntegrationTest):
 
         assert 'Successfully built' in lines[-1]['stream']
 
+    def test_build_with_dockerfile_empty_lines(self):
+        base_dir = tempfile.mkdtemp()
+        self.addCleanup(shutil.rmtree, base_dir)
+        with open(os.path.join(base_dir, 'Dockerfile'), 'w') as f:
+            f.write('FROM busybox\\n')
+        with open(os.path.join(base_dir, '.dockerignore'), 'w') as f:
+            f.write('\\n'.join([
+                '   ',
+                '',
+                '\\t\\t',
+                '\\t     ',
+            ]))
+
+        stream = self.client.build(
+            path=base_dir, stream=True, decode=True, nocache=True
+        )
+
+        lines = []
+        for chunk in stream:
+            lines.append(chunk)
+        assert 'Successfully built' in lines[-1]['stream']
+
     def test_build_gzip_custom_encoding(self):
         with self.assertRaises(errors.DockerException):
             self.client.build(path='.', gzip=True, encoding='text/html')
Repository: docker/docker-py
Issue: Push(stream=True) does not work anymore.

```
$ cat test.py 
import docker

c = docker.Client()
for line in c.push("test_image", stream=True):
    print line
$ sudo venv/bin/python test.py 
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    for line in c.push("test_image", stream=True):
  File "/home/{username}/docker-py/docker/client.py", line 230, in _stream_helper
    size = int(socket.readline(), 16)
IOError: [Errno 11] Resource temporarily unavailable
```

I suspect #117 or #123 broke this. Seems like it's a blocking vs nonblocking socket issue.


Changed files:
docker/client.py

diff --git a/docker/client.py b/docker/client.py
index 8c13ea2a..5ccf9988 100644
--- a/docker/client.py
+++ b/docker/client.py
@@ -227,7 +227,9 @@ class Client(requests.Session):
 
     def _stream_helper(self, response):
         """Generator for data coming from a chunked-encoded HTTP response."""
-        socket = self._stream_result_socket(response).makefile()
+        socket_fp = self._stream_result_socket(response)
+        socket_fp.setblocking(1)
+        socket = socket_fp.makefile()
         while True:
             size = int(socket.readline(), 16)
             if size <= 0:
Repository: docker/docker-py
Issue: logs(stream=True) broken for python 3.3

I'm unable to iterate over logs as a stream for a container in python 3.3. It seems like some of the private apis have changed. I poked around for a minute but this is over my head. I pip installed the master.zip on commit ef009e114a3be

Code to reproduce:

``` python
for chunk in d.logs(c, stream=True):
    print(chunk)
```

Error

``` python
 Traceback (most recent call last):
   File "/home/m/Code/dockerstuff/d.py", line 100, in main
     for chunk in d.logs(c, stream=True):
   File "/home/m/.virtualenvs/d/lib/python3.3/site-packages/docker/client.py", line 257, in _multiplexed_socket_stream_helper
     socket = self._stream_result_socket(response)
   File "/home/m/.virtualenvs/d/lib/python3.3/site-packages/docker/client.py", line 226, in _stream_result_socket
     return response.raw._fp.fp._sock
AttributeError: '_io.BufferedReader' object has no attribute '_sock'
```


Changed files:
docker/client.py

diff --git a/docker/client.py b/docker/client.py
index b1c85800..8cd2f535 100644
--- a/docker/client.py
+++ b/docker/client.py
@@ -228,7 +228,10 @@ class Client(requests.Session):
 
     def _get_raw_response_socket(self, response):
         self._raise_for_status(response)
-        return response.raw._fp.fp._sock
+        if six.PY3:
+            return response.raw._fp.fp.raw._sock
+        else:
+            return response.raw._fp.fp._sock
 
     def _stream_helper(self, response):
         """Generator for data coming from a chunked-encoded HTTP response."""
@@ -264,14 +267,19 @@ class Client(requests.Session):
         socket = self._get_raw_response_socket(response)
 
         def recvall(socket, size):
-            data = ''
+            blocks = []
             while size > 0:
                 block = socket.recv(size)
                 if not block:
                     return None
 
-                data += block
+                blocks.append(block)
                 size -= len(block)
+
+            sep = bytes() if six.PY3 else str()
+            data = sep.join(blocks)
+            if six.PY3:
+                data = data.decode('utf-8')
             return data
 
         while True:
Repository: docker/docker-py
Issue: streaming from build() is broken in 0.3.0

Some client code that was working fine w/ docker-py 0.2.3 now breaks on 0.3.0

A minimal test case looks like:

```
ubuntu@ip-10-77-1-34:/tmp/foo$ cat Dockerfile
FROM stackbrew/ubuntu:13.04
RUN echo "hello"
CMD /bin/bash

ubuntu@ip-10-77-1-34:/tmp/foo$ cat test.py
import docker

doc = docker.Client()
gen = doc.build(path='.', stream=True)
for line in gen:
    print line
```

Executing `test.py` under 0.2.3 builds the image fine.  Under 0.3.0, I get 

```
ubuntu@ip-10-77-1-34:/tmp/foo$ python test.py
{"stream":" ---\\u003e Using cache\\n"}

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    for line in gen:
  File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 239, in _stream_helper
    size = int(socket.readline(), 16)
ValueError: invalid literal for int() with base 16: ''
```

This is Ubuntu 12.04 w/ Docker 0.9.0


Changed files:
docker/client.py

diff --git a/docker/client.py b/docker/client.py
index d8f79c92..38355b09 100644
--- a/docker/client.py
+++ b/docker/client.py
@@ -233,17 +233,8 @@ class Client(requests.Session):
 
     def _stream_helper(self, response):
         """Generator for data coming from a chunked-encoded HTTP response."""
-        socket_fp = self._get_raw_response_socket(response)
-        socket_fp.setblocking(1)
-        socket = socket_fp.makefile()
-        while True:
-            size = int(socket.readline(), 16)
-            if size <= 0:
-                break
-            data = socket.readline()
-            if not data:
-                break
-            yield data
+        for line in response.iter_lines(chunk_size=32):
+            yield line
 
     def _multiplexed_buffer_helper(self, response):
         """A generator of multiplexed data blocks read from a buffered
@@ -349,6 +340,9 @@ class Client(requests.Session):
         else:
             context = utils.tar(path)
 
+        if utils.compare_version('1.8', self._version) >= 0:
+            stream = True
+
         u = self._url('/build')
         params = {
             't': tag,
@@ -372,7 +366,7 @@ class Client(requests.Session):
         if context is not None:
             context.close()
 
-        if stream or utils.compare_version('1.8', self._version) >= 0:
+        if stream:
             return self._stream_helper(response)
         else:
             output = self._result(response)
Repository: docker/docker-py
Issue: 'None' timeout breaks with Client.stop

Hi,

We are wotking on a script to automate some stuff using docker and docker-py in some point we execute some code inside docker, this command can take from a few minutes to a 5 or 6 hours.

I realized that I could do something like this:

``` python
container_name = 'container_name_or_id'
cli = Client(timeout=None)
output = cli.execute(container_name, 'ls')
```

And works as expected, but then the container have to be stopped and started (here I just put the specific code for a PoC):

``` python
from docker import Client

container_name = 'container_name_or_id'
cli = Client(timeout=None)

# Here goes a command that take a lot of time, not just a ls
output = cli.execute(container_name, 'ls')
cli.stop(container_name)
# Do some more stuff
cli.start(container_name)
```

But we get this:

```
Traceback (most recent call last):
  File "test_resume.py", line 48, in <module>
    cli.stop(container_name)
  File "/home/truiz/deployer/venv/lib/python2.7/site-packages/docker/client.py", line 923, in stop
    timeout=(timeout + self.timeout))
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
```

Is there any other way of setting an "infinite" timeout? or just no timeout for this long runnig scripts?

Regards


Changed files:
docker/client.py, tests/integration_test.py

diff --git a/docker/client.py b/docker/client.py
index f63da501..8bcc419e 100644
--- a/docker/client.py
+++ b/docker/client.py
@@ -1101,7 +1101,7 @@ class Client(requests.Session):
         url = self._url("/containers/{0}/stop".format(container))
 
         res = self._post(url, params=params,
-                         timeout=(timeout + self.timeout))
+                         timeout=(timeout + (self.timeout or 0)))
         self._raise_for_status(res)
 
     @check_resource
diff --git a/tests/integration_test.py b/tests/integration_test.py
index c9ab1405..4b9869e2 100644
--- a/tests/integration_test.py
+++ b/tests/integration_test.py
@@ -1467,6 +1467,11 @@ class TestRegressions(BaseTestCase):
         result = self.client.containers(all=True, trunc=True)
         self.assertEqual(len(result[0]['Id']), 12)
 
+    def test_649(self):
+        self.client.timeout = None
+        ctnr = self.client.create_container('busybox', ['sleep', '2'])
+        self.client.start(ctnr)
+        self.client.stop(ctnr)
 
 if __name__ == '__main__':
     c = docker.Client(base_url=DEFAULT_BASE_URL)
Repository: docker/docker-py
Issue: Slightly incorrect documentation for user parameter in create_container?

The documentation for `user` parameter in `create_container` says: 

`user (str or int): Username or UID`

However, supplying it as python's int(`client.create_container(user=1000, ...)`) gives 
`docker.errors.APIError: 500 Server Error: Internal Server Error ("json: cannot unmarshal number into Go value of type string")`

Supplying it as string works. So this code `client.create_container(user="1000", ...)` works fine. 

I guess it is a minor issue, though only because Celery printed the exception as "500 Server Error: Internal Server Error", so the critical piece of information was missing(`json: cannot unmarshal number into Go value of type string`). So I guess it is a minor issue, but I figured I should report it. 


Changed files:
tests/integration_test.py, docker/utils/utils.py

diff --git a/docker/utils/utils.py b/docker/utils/utils.py
index 8dc726b3..c49b3e58 100644
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -715,7 +715,7 @@ def create_container_config(
         'Hostname': hostname,
         'Domainname': domainname,
         'ExposedPorts': ports,
-        'User': user,
+        'User': six.text_type(user) if user else None,
         'Tty': tty,
         'OpenStdin': stdin_open,
         'StdinOnce': stdin_once,
diff --git a/tests/integration_test.py b/tests/integration_test.py
index fd4ff2d0..4fb2b8ff 100644
--- a/tests/integration_test.py
+++ b/tests/integration_test.py
@@ -1624,3 +1624,9 @@ class TestRegressions(BaseTestCase):
         ctnr = self.client.create_container('busybox', ['sleep', '2'])
         self.client.start(ctnr)
         self.client.stop(ctnr)
+
+    def test_715(self):
+        ctnr = self.client.create_container('busybox', ['id', '-u'], user=1000)
+        self.client.start(ctnr)
+        self.client.wait(ctnr)
+        assert self.client.logs(ctnr) == '1000\\n'
Repository: docker/docker-py
Issue: decode_auth function does not handle utf-8 logins or password

HI

I have found that the function **decode_auth** (line 96, [file](https://github.com/docker/docker-py/blob/master/docker/auth/auth.py)) fails when decoding UTF-8 passwords from the .dockercfg file, and **load_config** returning an empty config.

I have checked and docker hub can handle UTF-8 passwords, this code proves that:

``` python
# coding=utf-8
from docker import Client
cred = { 'username': <user>, 'password': <utf-8 password> }
c = Client(base_url='unix://var/run/docker.sock')
res = c.pull(repository='<private container>', tag='latest', auth_config=cred)
print(res)
```

Thank you


Changed files:
tests/unit/auth_test.py, docker/auth/auth.py

diff --git a/docker/auth/auth.py b/docker/auth/auth.py
index 2ed894ee..416dd7c4 100644
--- a/docker/auth/auth.py
+++ b/docker/auth/auth.py
@@ -96,7 +96,7 @@ def decode_auth(auth):
         auth = auth.encode('ascii')
     s = base64.b64decode(auth)
     login, pwd = s.split(b':', 1)
-    return login.decode('ascii'), pwd.decode('ascii')
+    return login.decode('utf8'), pwd.decode('utf8')
 
 
 def encode_header(auth):
diff --git a/tests/unit/auth_test.py b/tests/unit/auth_test.py
index 9f4d439b..67830381 100644
--- a/tests/unit/auth_test.py
+++ b/tests/unit/auth_test.py
@@ -316,3 +316,33 @@ class LoadConfigTest(base.Cleanup, base.BaseTestCase):
             self.assertEqual(cfg['password'], 'izayoi')
             self.assertEqual(cfg['email'], 'sakuya@scarlet.net')
             self.assertEqual(cfg.get('auth'), None)
+
+    def test_load_config_custom_config_env_utf8(self):
+        folder = tempfile.mkdtemp()
+        self.addCleanup(shutil.rmtree, folder)
+
+        dockercfg_path = os.path.join(folder, 'config.json')
+        registry = 'https://your.private.registry.io'
+        auth_ = base64.b64encode(
+            b'sakuya\\xc3\\xa6:izayoi\\xc3\\xa6').decode('ascii')
+        config = {
+            'auths': {
+                registry: {
+                    'auth': '{0}'.format(auth_),
+                    'email': 'sakuya@scarlet.net'
+                }
+            }
+        }
+
+        with open(dockercfg_path, 'w') as f:
+            json.dump(config, f)
+
+        with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}):
+            cfg = auth.load_config(None)
+            assert registry in cfg
+            self.assertNotEqual(cfg[registry], None)
+            cfg = cfg[registry]
+            self.assertEqual(cfg['username'], b'sakuya\\xc3\\xa6'.decode('utf8'))
+            self.assertEqual(cfg['password'], b'izayoi\\xc3\\xa6'.decode('utf8'))
+            self.assertEqual(cfg['email'], 'sakuya@scarlet.net')
+            self.assertEqual(cfg.get('auth'), None)