internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: docker/docker-py

Issue:
Support LinkLocalIps in connect_container_to_network
https://github.com/docker/docker/pull/23415



Discussion:

Resolving patch:
diff --git a/docker/api/network.py b/docker/api/network.py
--- a/docker/api/network.py
+++ b/docker/api/network.py
@@ -60,12 +60,13 @@ def inspect_network(self, net_id):
     @minimum_version('1.21')
     def connect_container_to_network(self, container, net_id,
                                      ipv4_address=None, ipv6_address=None,
-                                     aliases=None, links=None):
+                                     aliases=None, links=None,
+                                     link_local_ips=None):
         data = {
             "Container": container,
             "EndpointConfig": self.create_endpoint_config(
                 aliases=aliases, links=links, ipv4_address=ipv4_address,
-                ipv6_address=ipv6_address
+                ipv6_address=ipv6_address, link_local_ips=link_local_ips
             ),
         }
 
diff --git a/docker/utils/utils.py b/docker/utils/utils.py
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -873,7 +873,8 @@ def create_networking_config(endpoints_config=None):
 
 
 def create_endpoint_config(version, aliases=None, links=None,
-                           ipv4_address=None, ipv6_address=None):
+                           ipv4_address=None, ipv6_address=None,
+                           link_local_ips=None):
     if version_lt(version, '1.22'):
         raise errors.InvalidVersion(
             'Endpoint config is not supported for API version < 1.22'
@@ -896,6 +897,13 @@ def create_endpoint_config(version, aliases=None, links=None,
     if ipam_config:
         endpoint_config['IPAMConfig'] = ipam_config
 
+    if link_local_ips is not None:
+        if version_lt(version, '1.24'):
+            raise errors.InvalidVersion(
+                'link_local_ips is not supported for API version < 1.24'
+            )
+        endpoint_config['LinkLocalIPs'] = link_local_ips
+
     return endpoint_config
 
 


Test patch:
Repository: docker/docker-py

Issue:
Requests v2.11.0 causes breakage
This is a known issue within requests and looks like it will be fixed in v2.11.1. Documenting for the benefit of anyone else who runs into this :).

After a recent pip upgrade I found that docker-py was passing along an error from requests:

File "/usr/local/lib/python2.7/dist-packages/docker/client.py", line 307, in _stream_raw_result
   for out in response.iter_content(chunk_size=1, decode_unicode=True):
 File "/usr/local/lib/python2.7/dist-packages/requests/utils.py", line 372, in stream_decode_response_unicode
   raise UnicodeError("Unable to decode contents with encoding %s." % encoding)
UnicodeError: Unable to decode contents with encoding None.

This has already been reported to requests (https://github.com/kennethreitz/requests/issues/3481) and fixed (https://github.com/kennethreitz/requests/commit/d7f56ba9383575a6b7d361db0123a93c70a2b42f) for the next version.

If you are running into this issue, the easiest fix for now appears to be reverting to a pre 2.11 version of requests.



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -9,7 +9,7 @@
 SOURCE_DIR = os.path.join(ROOT_DIR)
 
 requirements = [
-    'requests >= 2.5.2',
+    'requests >= 2.5.2, < 2.11',
     'six >= 1.4.0',
     'websocket-client >= 0.32.0',
 ]


Test patch:
Repository: docker/docker-py

Issue:
Feature Request: docker.from_env(version='auto')
Feature request to add auto api version support for `docker.from_env()` similar to `docker.Client(version='auto')`?

I noticed that one of the suggestions from #402 for the `version='auto'` option was now available for `docker.Client()` but doesn't work for `docker.from_env()`.



Discussion:
Agreed.
For now, the current workaround would be

``` python
from docker import Client
from docker.utils import kwargs_from_env

c = Client(version='auto', **kwargs_from_env())
```


Resolving patch:
diff --git a/docker/client.py b/docker/client.py
--- a/docker/client.py
+++ b/docker/client.py
@@ -114,7 +114,8 @@ def __init__(self, base_url=None, version=None,
 
     @classmethod
     def from_env(cls, **kwargs):
-        return cls(**kwargs_from_env(**kwargs))
+        version = kwargs.pop('version', None)
+        return cls(version=version, **kwargs_from_env(**kwargs))
 
     def _retrieve_server_version(self):
         try:


Test patch:
diff --git a/tests/unit/client_test.py b/tests/unit/client_test.py
--- a/tests/unit/client_test.py
+++ b/tests/unit/client_test.py
@@ -25,6 +25,14 @@ def test_from_env(self):
         client = Client.from_env()
         self.assertEqual(client.base_url, "https://192.168.59.103:2376")
 
+    def test_from_env_with_version(self):
+        os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376',
+                          DOCKER_CERT_PATH=TEST_CERT_DIR,
+                          DOCKER_TLS_VERIFY='1')
+        client = Client.from_env(version='2.32')
+        self.assertEqual(client.base_url, "https://192.168.59.103:2376")
+        self.assertEqual(client._version, '2.32')
+
 
 class DisableSocketTest(base.BaseTestCase):
     class DummySocket(object):
Repository: docker/docker-py

Issue:
support PidsLimit in host config

support PidsLimit in host config



Discussion:

Resolving patch:
diff --git a/docker/utils/utils.py b/docker/utils/utils.py
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -623,7 +623,7 @@ def create_host_config(binds=None, port_bindings=None, lxc_conf=None,
                        device_write_iops=None, oom_kill_disable=False,
                        shm_size=None, sysctls=None, version=None, tmpfs=None,
                        oom_score_adj=None, dns_opt=None, cpu_shares=None,
-                       cpuset_cpus=None, userns_mode=None):
+                       cpuset_cpus=None, userns_mode=None, pids_limit=None):
 
     host_config = {}
 
@@ -904,6 +904,13 @@ def create_host_config(binds=None, port_bindings=None, lxc_conf=None,
             raise host_config_value_error("userns_mode", userns_mode)
         host_config['UsernsMode'] = userns_mode
 
+    if pids_limit:
+        if not isinstance(pids_limit, int):
+            raise host_config_type_error('pids_limit', pids_limit, 'int')
+        if version_lt(version, '1.23'):
+            raise host_config_version_error('pids_limit', '1.23')
+        host_config["PidsLimit"] = pids_limit
+
     return host_config
 
 


Test patch:
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py
--- a/tests/unit/utils_test.py
+++ b/tests/unit/utils_test.py
@@ -185,6 +185,15 @@ def test_create_host_config_with_kernel_memory(self):
             InvalidVersion, lambda: create_host_config(
                 version='1.20', kernel_memory=67108864))
 
+    def test_create_host_config_with_pids_limit(self):
+        config = create_host_config(version='1.23', pids_limit=1024)
+        self.assertEqual(config.get('PidsLimit'), 1024)
+
+        with pytest.raises(InvalidVersion):
+            create_host_config(version='1.22', pids_limit=1024)
+        with pytest.raises(TypeError):
+            create_host_config(version='1.22', pids_limit='1024')
+
 
 class UlimitTest(base.BaseTestCase):
     def test_create_host_config_dict_ulimit(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.



Discussion:

Resolving patch:
diff --git a/docker/transport/npipesocket.py b/docker/transport/npipesocket.py
--- a/docker/transport/npipesocket.py
+++ b/docker/transport/npipesocket.py
@@ -94,7 +94,7 @@ def makefile(self, mode=None, bufsize=None):
         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)
 


Test patch:
Repository: docker/docker-py

Issue:
New 1.10.0 release breaks ansible
Error:
`{"changed": false, "failed": true, "msg": "Failed to import docker-py - No module named types. Try `pip install docker-py`"}`



Discussion:
That's weird. `docker.types` is present and declared in `setup.py`. Installing and importing it in a fresh virtualenv also doesn't seem to raise any issue. Are there more details you can share on what's triggering the issue?

This _should_ reproduce it:

```
- hosts: my_host
  roles:
     - angstwad.docker_ubuntu
- hosts: my_host
  tasks:
    - name: login
      docker_login:
        username: foo
        password: bar
        email: a@a.com 
```

**Temporary fix**
Downgrade to 1.9.0:

```
 roles:
    - { role: angstwad.docker_ubuntu, pip_version_docker_py: 1.9.0 }
```

+1

+1

I guess I broke this https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/docker_common.py#L38 - my bad. I'll see if I can release a 1.10.1 with a fix.


Resolving patch:
diff --git a/docker/utils/types.py b/docker/utils/types.py
new file mode 100644
--- /dev/null
+++ b/docker/utils/types.py
@@ -0,0 +1,7 @@
+# Compatibility module. See https://github.com/docker/docker-py/issues/1196
+
+import warnings
+
+from ..types import Ulimit, LogConfig  # flake8: noqa
+
+warnings.warn('docker.utils.types is now docker.types', ImportWarning)


Test patch:
Repository: docker/docker-py

Issue:
Issue with requests dependency
I found that commit 95d9306d2a1fd22dffb12a0548abf2d2f744ed9d excludes requests 2.11 for a bug that is fixed now on requests 2.11.1. And that's giving me a version conflict with another of the modules on my project:

```
pkg_resources.ContextualVersionConflict: (requests 2.11.1 (..............), Requirement.parse('requests<2.11,>=2.5.2'), {'docker-py'})
```

Can we allow requests 2.11.1 ?



Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -9,7 +9,7 @@
 SOURCE_DIR = os.path.join(ROOT_DIR)
 
 requirements = [
-    'requests >= 2.5.2, < 2.11',
+    'requests >= 2.5.2',
     'six >= 1.4.0',
     'websocket-client >= 0.32.0',
     'docker-pycreds >= 0.2.1'


Test patch:
Repository: docker/docker-py

Issue:
Client.build should +x all context files on Windows
docker/compose#3716



Discussion:

Resolving patch:
diff --git a/docker/utils/utils.py b/docker/utils/utils.py
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -4,6 +4,7 @@
 import os.path
 import json
 import shlex
+import sys
 import tarfile
 import tempfile
 import warnings
@@ -92,7 +93,21 @@ def tar(path, exclude=None, dockerfile=None, fileobj=None, gzip=False):
     exclude = exclude or []
 
     for path in sorted(exclude_paths(root, exclude, dockerfile=dockerfile)):
-        t.add(os.path.join(root, path), arcname=path, recursive=False)
+        i = t.gettarinfo(os.path.join(root, path), arcname=path)
+
+        if sys.platform == 'win32':
+            # Windows doesn't keep track of the execute bit, so we make files
+            # and directories executable by default.
+            i.mode = i.mode & 0o755 | 0o111
+
+        try:
+            # We open the file object in binary mode for Windows support.
+            f = open(os.path.join(root, path), 'rb')
+        except IOError:
+            # When we encounter a directory the file object is set to None.
+            f = None
+
+        t.addfile(i, f)
 
     t.close()
     fileobj.seek(0)


Test patch:
Repository: docker/docker-py

Issue:
create a sans-io docker client class and impliment Client with blocking requests
use https://github.com/mikeal/deferred to create a sans-io version of Client (SansIOClient) that requires something like:

``` python
class SimpleStream(object):
    def next(self) -> Deferred:
        ...

class IOAdapter(object):
    def request(self, **kwargs) -> Deferred:
        ...

    def stream(self, **kwargs) -> SimpleStream:
        ...

    def unwrap_deferred(self, deferred: Deferred) -> Any:
        ...
```

and then implement it with something like:

``` python
class BlockingSimpleStream(SimpleStream):
    def __init__(self, stream):
        self.generator = _stream_helper(stream):
    def next(self) -> Deferred:
        return deferred.succeeded(next(self.generator))

class BlockingIOAdapter(IOAdapter):
    def __init__(session: requests.Session):
        self.session = session

    def request(self, **kwargs) -> Deferred:
        return deferred.execute(self.session.request, **kwargs)

    def stream(self, **kwargs) -> BlockingSimpleStream:
        return BlockingSimpleStream(self.session.request(**kwargs, stream=True))

    def unwrap_deferred(self, d: Deferred):
        return deferred.waitForDeferred(d).getResult()
```



Discussion:
This way someone can come and make an asyncio IOAdapter adapter to fix #327

This won't change too much of the implimentation of api classes, they will just need to add @defered.inlineCallbacks to their methods, and then instead of:

``` python
resp = self._request(...);
```

do:

``` python
resp = yield self._request(...);
```

@bfirsh is this something you'd like a PR on?


Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -33,10 +33,20 @@
     test_requirements = [line for line in test_reqs_txt]
 
 
+long_description = ''
+try:
+    with open('./README.rst') as readme_rst:
+        long_description = readme_rst.read()
+except IOError:
+    # README.rst is only generated on release. Its absence should not prevent
+    # setup.py from working properly.
+    pass
+
 setup(
     name="docker-py",
     version=version,
     description="Python client for Docker.",
+    long_description=long_description,
     url='https://github.com/docker/docker-py/',
     packages=[
         'docker', 'docker.api', 'docker.auth', 'docker.transport',
@@ -64,4 +74,6 @@
         'Topic :: Utilities',
         'License :: OSI Approved :: Apache Software License',
     ],
+    maintainer='Joffrey F',
+    maintainer_email='joffrey@docker.com',
 )


Test patch:
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.



Discussion:
Tentatively using the python3 label, but I'm not sure yet what we're dealing with here. We did change the log streaming code recently so it's possible we missed something.

I actually got a different error when trying this on Python 2.7.12, but amusingly in the same area. :-) I also confirmed that this works fine on the previous docker-py 1.9.0.

```
Traceback (most recent call last):
  File "/Users/michael/work/oss/marina/marina/build.py", line 697, in watcher
    if encoding:
  File ".venv/lib/python2.7/site-packages/docker/utils/socket.py", line 67, in frames_iter
    yield read(socket, n)
  File ".venv/lib/python2.7/site-packages/docker/utils/socket.py", line 24, in read
    return socket.recv(n)
OverflowError: signed integer is greater than maximum
```

Hm, interesting. Might be the same underlying issue presented differently. I'll look into it. Thanks for the report!


Resolving patch:
diff --git a/docker/utils/socket.py b/docker/utils/socket.py
--- 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


Test patch:
Repository: docker/docker-py

Issue:
Client should tolerate trailing slashes in base_url
docker/compose#3869



Discussion:

Resolving patch:
diff --git a/docker/utils/utils.py b/docker/utils/utils.py
--- a/docker/utils/utils.py
+++ b/docker/utils/utils.py
@@ -453,8 +453,8 @@ def parse_host(addr, is_win32=False, tls=False):
             "Bind address needs a port: {0}".format(addr))
 
     if proto == "http+unix" or proto == 'npipe':
-        return "{0}://{1}".format(proto, host)
-    return "{0}://{1}:{2}{3}".format(proto, host, port, path)
+        return "{0}://{1}".format(proto, host).rstrip('/')
+    return "{0}://{1}:{2}{3}".format(proto, host, port, path).rstrip('/')
 
 
 def parse_devices(devices):


Test patch:
diff --git a/tests/unit/utils_test.py b/tests/unit/utils_test.py
--- a/tests/unit/utils_test.py
+++ b/tests/unit/utils_test.py
@@ -522,6 +522,11 @@ def test_parse_host_tls_tcp_proto(self):
         expected_result = 'https://myhost.docker.net:3348'
         assert parse_host(host_value, tls=True) == expected_result
 
+    def test_parse_host_trailing_slash(self):
+        host_value = 'tcp://myhost.docker.net:2376/'
+        expected_result = 'http://myhost.docker.net:2376'
+        assert parse_host(host_value) == expected_result
+
 
 class ParseRepositoryTagTest(base.BaseTestCase):
     sha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
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.


Discussion:

Resolving patch:
diff --git a/docker/transport/npipesocket.py b/docker/transport/npipesocket.py
--- a/docker/transport/npipesocket.py
+++ b/docker/transport/npipesocket.py
@@ -170,13 +170,16 @@ def setblocking(self, flag):
 
     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


Test patch:
Repository: docker/docker-py

Issue:
Add docker network IPAM options parameter
IPAM driver missing options

supports an options field in the IPAM config 
It introduced in API v1.22.

```
POST /networks/create Now supports an options field in the IPAM config that provides options for custom IPAM plugins.
```



Discussion:
Fixes #1165 



Resolving patch:
diff --git a/docker/types/networks.py b/docker/types/networks.py
--- a/docker/types/networks.py
+++ b/docker/types/networks.py
@@ -50,6 +50,8 @@ class IPAMConfig(dict):
         driver (str): The IPAM driver to use. Defaults to ``default``.
         pool_configs (list): A list of pool configurations
           (:py:class:`~docker.types.IPAMPool`). Defaults to empty list.
+        options (dict): Driver options as a key-value dictionary.
+          Defaults to `None`.
 
     Example:
 
@@ -57,12 +59,17 @@ class IPAMConfig(dict):
         >>> network = client.create_network('network1', ipam=ipam_config)
 
     """
-    def __init__(self, driver='default', pool_configs=None):
+    def __init__(self, driver='default', pool_configs=None, options=None):
         self.update({
             'Driver': driver,
             'Config': pool_configs or []
         })
 
+        if options:
+            if not isinstance(options, dict):
+                raise TypeError('IPAMConfig options must be a dictionary')
+            self['Options'] = options
+
 
 class IPAMPool(dict):
     """


Test patch:
diff --git a/tests/unit/api_network_test.py b/tests/unit/api_network_test.py
--- a/tests/unit/api_network_test.py
+++ b/tests/unit/api_network_test.py
@@ -100,7 +100,7 @@ def test_create_network(self):
                             "Gateway": "192.168.52.254",
                             "Subnet": "192.168.52.0/24",
                             "AuxiliaryAddresses": None,
-                        }]
+                        }],
                     }
                 })
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):
```


Discussion:
Thanks for the report, and the patch!
just enough
```
diff --git a/docker/models/images.py b/docker/models/images.py
index 32068e6..21139ae 100644
--- a/docker/models/images.py
+++ b/docker/models/images.py
@@ -31,7 +31,7 @@ def tags(self):
         The image's tags.
         """
         return [
-            tag for tag in self.attrs.get('RepoTags', [])
+            tag for tag in (self.attrs.get('RepoTags') or [])
             if tag != '<none>:<none>'
         ]
```

Resolving patch:
diff --git a/docker/models/images.py b/docker/models/images.py
--- a/docker/models/images.py
+++ b/docker/models/images.py
@@ -30,10 +30,10 @@ def tags(self):
         """
         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):
         """


Test patch:
diff --git a/tests/unit/models_images_test.py b/tests/unit/models_images_test.py
--- a/tests/unit/models_images_test.py
+++ b/tests/unit/models_images_test.py
@@ -83,6 +83,11 @@ def test_tags(self):
         })
         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)