We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Docker inspect fails when running with Docker in Docker
When trying to run pre commits with `docker_image` language via GitLabs Docker in Docker approach the docker inspect fails, and so pre-commit throws an error when trying to get the mount path.

The [code](https://github.com/pre-commit/pre-commit/blob/fe436f1eb09dfdd67032b4f9f8dfa543fb99cf06/pre_commit/languages/docker.py#L39) for this already has a fall back of "return path" but doesn't handle the docker command failing.

Could the code for this be modified to handle the docker inspect failing?

More details of docker in docker are [here](https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#use-the-docker-executor-with-the-docker-image-docker-in-docker)


Full logs of the failure:


### version information

```
pre-commit version: 2.13.0
sys.version:
    3.6.9 (default, Jan 26 2021, 15:33:00) 
    [GCC 8.4.0]
sys.executable: /usr/bin/python3
os.name: posix
sys.platform: linux
```

### error information

```
An unexpected error has occurred: CalledProcessError: command: ('/usr/bin/docker', 'inspect', 'runner-dmrvfsu-project-35395-concurrent-0')
return code: 1
expected return code: 0
stdout:
    []
    
stderr:
    Error: No such object: runner-dmrvfsu-project-35395-concurrent-0
    
```

```
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/error_handler.py", line 65, in error_handler
    yield
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/main.py", line 385, in main
    return run(args.config, store, args)
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/commands/run.py", line 410, in run
    return _run_hooks(config, hooks, skips, args, environ)
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/commands/run.py", line 288, in _run_hooks
    verbose=args.verbose, use_color=args.color,
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/commands/run.py", line 194, in _run_single_hook
    retcode, out = language.run_hook(hook, filenames, use_color)
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/languages/docker_image.py", line 19, in run_hook
    cmd = docker_cmd() + hook.cmd
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/languages/docker.py", line 107, in docker_cmd
    '-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z',
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/languages/docker.py", line 34, in _get_docker_path
    _, out, _ = cmd_output_b('docker', 'inspect', hostname)
  File "/usr/local/lib/python3.6/dist-packages/pre_commit/util.py", line 154, in cmd_output_b
    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)
pre_commit.util.CalledProcessError: command: ('/usr/bin/docker', 'inspect', 'runner-dmrvfsu-project-35395-concurrent-0')
return code: 1
expected return code: 0
stdout:
    []
    
stderr:
    Error: No such object: runner-dmrvfsu-project-35395-concurrent-0
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pre_commit/languages/docker.py`
Content:
```
1 import hashlib
2 import json
3 import os
4 from typing import Sequence
5 from typing import Tuple
6 
7 import pre_commit.constants as C
8 from pre_commit.hook import Hook
9 from pre_commit.languages import helpers
10 from pre_commit.prefix import Prefix
11 from pre_commit.util import clean_path_on_failure
12 from pre_commit.util import cmd_output_b
13 
14 ENVIRONMENT_DIR = 'docker'
15 PRE_COMMIT_LABEL = 'PRE_COMMIT'
16 get_default_version = helpers.basic_get_default_version
17 healthy = helpers.basic_healthy
18 
19 
20 def _is_in_docker() -> bool:
21     try:
22         with open('/proc/1/cgroup', 'rb') as f:
23             return b'docker' in f.read()
24     except FileNotFoundError:
25         return False
26 
27 
28 def _get_container_id() -> str:
29     # It's assumed that we already check /proc/1/cgroup in _is_in_docker. The
30     # cpuset cgroup controller existed since cgroups were introduced so this
31     # way of getting the container ID is pretty reliable.
32     with open('/proc/1/cgroup', 'rb') as f:
33         for line in f.readlines():
34             if line.split(b':')[1] == b'cpuset':
35                 return os.path.basename(line.split(b':')[2]).strip().decode()
36     raise RuntimeError('Failed to find the container ID in /proc/1/cgroup.')
37 
38 
39 def _get_docker_path(path: str) -> str:
40     if not _is_in_docker():
41         return path
42 
43     container_id = _get_container_id()
44 
45     _, out, _ = cmd_output_b('docker', 'inspect', container_id)
46 
47     container, = json.loads(out)
48     for mount in container['Mounts']:
49         src_path = mount['Source']
50         to_path = mount['Destination']
51         if os.path.commonpath((path, to_path)) == to_path:
52             # So there is something in common,
53             # and we can proceed remapping it
54             return path.replace(to_path, src_path)
55     # we're in Docker, but the path is not mounted, cannot really do anything,
56     # so fall back to original path
57     return path
58 
59 
60 def md5(s: str) -> str:  # pragma: win32 no cover
61     return hashlib.md5(s.encode()).hexdigest()
62 
63 
64 def docker_tag(prefix: Prefix) -> str:  # pragma: win32 no cover
65     md5sum = md5(os.path.basename(prefix.prefix_dir)).lower()
66     return f'pre-commit-{md5sum}'
67 
68 
69 def build_docker_image(
70         prefix: Prefix,
71         *,
72         pull: bool,
73 ) -> None:  # pragma: win32 no cover
74     cmd: Tuple[str, ...] = (
75         'docker', 'build',
76         '--tag', docker_tag(prefix),
77         '--label', PRE_COMMIT_LABEL,
78     )
79     if pull:
80         cmd += ('--pull',)
81     # This must come last for old versions of docker.  See #477
82     cmd += ('.',)
83     helpers.run_setup_cmd(prefix, cmd)
84 
85 
86 def install_environment(
87         prefix: Prefix, version: str, additional_dependencies: Sequence[str],
88 ) -> None:  # pragma: win32 no cover
89     helpers.assert_version_default('docker', version)
90     helpers.assert_no_additional_deps('docker', additional_dependencies)
91 
92     directory = prefix.path(
93         helpers.environment_dir(ENVIRONMENT_DIR, C.DEFAULT),
94     )
95 
96     # Docker doesn't really have relevant disk environment, but pre-commit
97     # still needs to cleanup its state files on failure
98     with clean_path_on_failure(directory):
99         build_docker_image(prefix, pull=True)
100         os.mkdir(directory)
101 
102 
103 def get_docker_user() -> Tuple[str, ...]:  # pragma: win32 no cover
104     try:
105         return ('-u', f'{os.getuid()}:{os.getgid()}')
106     except AttributeError:
107         return ()
108 
109 
110 def docker_cmd() -> Tuple[str, ...]:  # pragma: win32 no cover
111     return (
112         'docker', 'run',
113         '--rm',
114         *get_docker_user(),
115         # https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from
116         # The `Z` option tells Docker to label the content with a private
117         # unshared label. Only the current container can use a private volume.
118         '-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z',
119         '--workdir', '/src',
120     )
121 
122 
123 def run_hook(
124         hook: Hook,
125         file_args: Sequence[str],
126         color: bool,
127 ) -> Tuple[int, bytes]:  # pragma: win32 no cover
128     # Rebuild the docker image in case it has gone missing, as many people do
129     # automated cleanup of docker images.
130     build_docker_image(hook.prefix, pull=False)
131 
132     entry_exe, *cmd_rest = hook.cmd
133 
134     entry_tag = ('--entrypoint', entry_exe, docker_tag(hook.prefix))
135     cmd = (*docker_cmd(), *entry_tag, *cmd_rest)
136     return helpers.run_xargs(hook, cmd, file_args, color=color)
137
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pre_commit/languages/docker.py b/pre_commit/languages/docker.py
--- a/pre_commit/languages/docker.py
+++ b/pre_commit/languages/docker.py
@@ -8,6 +8,7 @@
 from pre_commit.hook import Hook
 from pre_commit.languages import helpers
 from pre_commit.prefix import Prefix
+from pre_commit.util import CalledProcessError
 from pre_commit.util import clean_path_on_failure
 from pre_commit.util import cmd_output_b
 
@@ -42,7 +43,11 @@
 
     container_id = _get_container_id()
 
-    _, out, _ = cmd_output_b('docker', 'inspect', container_id)
+    try:
+        _, out, _ = cmd_output_b('docker', 'inspect', container_id)
+    except CalledProcessError:
+        # self-container was not visible from here (perhaps docker-in-docker)
+        return path
 
     container, = json.loads(out)
     for mount in container['Mounts']:

{"golden_diff": "diff --git a/pre_commit/languages/docker.py b/pre_commit/languages/docker.py\n--- a/pre_commit/languages/docker.py\n+++ b/pre_commit/languages/docker.py\n@@ -8,6 +8,7 @@\n from pre_commit.hook import Hook\n from pre_commit.languages import helpers\n from pre_commit.prefix import Prefix\n+from pre_commit.util import CalledProcessError\n from pre_commit.util import clean_path_on_failure\n from pre_commit.util import cmd_output_b\n \n@@ -42,7 +43,11 @@\n \n     container_id = _get_container_id()\n \n-    _, out, _ = cmd_output_b('docker', 'inspect', container_id)\n+    try:\n+        _, out, _ = cmd_output_b('docker', 'inspect', container_id)\n+    except CalledProcessError:\n+        # self-container was not visible from here (perhaps docker-in-docker)\n+        return path\n \n     container, = json.loads(out)\n     for mount in container['Mounts']:\n", "issue": "Docker inspect fails when running with Docker in Docker\nWhen trying to run pre commits with `docker_image` language via GitLabs Docker in Docker approach the docker inspect fails, and so pre-commit throws an error when trying to get the mount path.\r\n\r\nThe [code](https://github.com/pre-commit/pre-commit/blob/fe436f1eb09dfdd67032b4f9f8dfa543fb99cf06/pre_commit/languages/docker.py#L39) for this already has a fall back of \"return path\" but doesn't handle the docker command failing.\r\n\r\nCould the code for this be modified to handle the docker inspect failing?\r\n\r\nMore details of docker in docker are [here](https://docs.gitlab.com/ee/ci/docker/using_docker_build.html#use-the-docker-executor-with-the-docker-image-docker-in-docker)\r\n\r\n\r\nFull logs of the failure:\r\n\r\n\r\n### version information\r\n\r\n```\r\npre-commit version: 2.13.0\r\nsys.version:\r\n    3.6.9 (default, Jan 26 2021, 15:33:00) \r\n    [GCC 8.4.0]\r\nsys.executable: /usr/bin/python3\r\nos.name: posix\r\nsys.platform: linux\r\n```\r\n\r\n### error information\r\n\r\n```\r\nAn unexpected error has occurred: CalledProcessError: command: ('/usr/bin/docker', 'inspect', 'runner-dmrvfsu-project-35395-concurrent-0')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout:\r\n    []\r\n    \r\nstderr:\r\n    Error: No such object: runner-dmrvfsu-project-35395-concurrent-0\r\n    \r\n```\r\n\r\n```\r\nTraceback (most recent call last):\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/error_handler.py\", line 65, in error_handler\r\n    yield\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/main.py\", line 385, in main\r\n    return run(args.config, store, args)\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/commands/run.py\", line 410, in run\r\n    return _run_hooks(config, hooks, skips, args, environ)\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/commands/run.py\", line 288, in _run_hooks\r\n    verbose=args.verbose, use_color=args.color,\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/commands/run.py\", line 194, in _run_single_hook\r\n    retcode, out = language.run_hook(hook, filenames, use_color)\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/languages/docker_image.py\", line 19, in run_hook\r\n    cmd = docker_cmd() + hook.cmd\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/languages/docker.py\", line 107, in docker_cmd\r\n    '-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z',\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/languages/docker.py\", line 34, in _get_docker_path\r\n    _, out, _ = cmd_output_b('docker', 'inspect', hostname)\r\n  File \"/usr/local/lib/python3.6/dist-packages/pre_commit/util.py\", line 154, in cmd_output_b\r\n    raise CalledProcessError(returncode, cmd, retcode, stdout_b, stderr_b)\r\npre_commit.util.CalledProcessError: command: ('/usr/bin/docker', 'inspect', 'runner-dmrvfsu-project-35395-concurrent-0')\r\nreturn code: 1\r\nexpected return code: 0\r\nstdout:\r\n    []\r\n    \r\nstderr:\r\n    Error: No such object: runner-dmrvfsu-project-35395-concurrent-0\r\n```\n", "before_files": [{"content": "import hashlib\nimport json\nimport os\nfrom typing import Sequence\nfrom typing import Tuple\n\nimport pre_commit.constants as C\nfrom pre_commit.hook import Hook\nfrom pre_commit.languages import helpers\nfrom pre_commit.prefix import Prefix\nfrom pre_commit.util import clean_path_on_failure\nfrom pre_commit.util import cmd_output_b\n\nENVIRONMENT_DIR = 'docker'\nPRE_COMMIT_LABEL = 'PRE_COMMIT'\nget_default_version = helpers.basic_get_default_version\nhealthy = helpers.basic_healthy\n\n\ndef _is_in_docker() -> bool:\n    try:\n        with open('/proc/1/cgroup', 'rb') as f:\n            return b'docker' in f.read()\n    except FileNotFoundError:\n        return False\n\n\ndef _get_container_id() -> str:\n    # It's assumed that we already check /proc/1/cgroup in _is_in_docker. The\n    # cpuset cgroup controller existed since cgroups were introduced so this\n    # way of getting the container ID is pretty reliable.\n    with open('/proc/1/cgroup', 'rb') as f:\n        for line in f.readlines():\n            if line.split(b':')[1] == b'cpuset':\n                return os.path.basename(line.split(b':')[2]).strip().decode()\n    raise RuntimeError('Failed to find the container ID in /proc/1/cgroup.')\n\n\ndef _get_docker_path(path: str) -> str:\n    if not _is_in_docker():\n        return path\n\n    container_id = _get_container_id()\n\n    _, out, _ = cmd_output_b('docker', 'inspect', container_id)\n\n    container, = json.loads(out)\n    for mount in container['Mounts']:\n        src_path = mount['Source']\n        to_path = mount['Destination']\n        if os.path.commonpath((path, to_path)) == to_path:\n            # So there is something in common,\n            # and we can proceed remapping it\n            return path.replace(to_path, src_path)\n    # we're in Docker, but the path is not mounted, cannot really do anything,\n    # so fall back to original path\n    return path\n\n\ndef md5(s: str) -> str:  # pragma: win32 no cover\n    return hashlib.md5(s.encode()).hexdigest()\n\n\ndef docker_tag(prefix: Prefix) -> str:  # pragma: win32 no cover\n    md5sum = md5(os.path.basename(prefix.prefix_dir)).lower()\n    return f'pre-commit-{md5sum}'\n\n\ndef build_docker_image(\n        prefix: Prefix,\n        *,\n        pull: bool,\n) -> None:  # pragma: win32 no cover\n    cmd: Tuple[str, ...] = (\n        'docker', 'build',\n        '--tag', docker_tag(prefix),\n        '--label', PRE_COMMIT_LABEL,\n    )\n    if pull:\n        cmd += ('--pull',)\n    # This must come last for old versions of docker.  See #477\n    cmd += ('.',)\n    helpers.run_setup_cmd(prefix, cmd)\n\n\ndef install_environment(\n        prefix: Prefix, version: str, additional_dependencies: Sequence[str],\n) -> None:  # pragma: win32 no cover\n    helpers.assert_version_default('docker', version)\n    helpers.assert_no_additional_deps('docker', additional_dependencies)\n\n    directory = prefix.path(\n        helpers.environment_dir(ENVIRONMENT_DIR, C.DEFAULT),\n    )\n\n    # Docker doesn't really have relevant disk environment, but pre-commit\n    # still needs to cleanup its state files on failure\n    with clean_path_on_failure(directory):\n        build_docker_image(prefix, pull=True)\n        os.mkdir(directory)\n\n\ndef get_docker_user() -> Tuple[str, ...]:  # pragma: win32 no cover\n    try:\n        return ('-u', f'{os.getuid()}:{os.getgid()}')\n    except AttributeError:\n        return ()\n\n\ndef docker_cmd() -> Tuple[str, ...]:  # pragma: win32 no cover\n    return (\n        'docker', 'run',\n        '--rm',\n        *get_docker_user(),\n        # https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from\n        # The `Z` option tells Docker to label the content with a private\n        # unshared label. Only the current container can use a private volume.\n        '-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z',\n        '--workdir', '/src',\n    )\n\n\ndef run_hook(\n        hook: Hook,\n        file_args: Sequence[str],\n        color: bool,\n) -> Tuple[int, bytes]:  # pragma: win32 no cover\n    # Rebuild the docker image in case it has gone missing, as many people do\n    # automated cleanup of docker images.\n    build_docker_image(hook.prefix, pull=False)\n\n    entry_exe, *cmd_rest = hook.cmd\n\n    entry_tag = ('--entrypoint', entry_exe, docker_tag(hook.prefix))\n    cmd = (*docker_cmd(), *entry_tag, *cmd_rest)\n    return helpers.run_xargs(hook, cmd, file_args, color=color)\n", "path": "pre_commit/languages/docker.py"}], "after_files": [{"content": "import hashlib\nimport json\nimport os\nfrom typing import Sequence\nfrom typing import Tuple\n\nimport pre_commit.constants as C\nfrom pre_commit.hook import Hook\nfrom pre_commit.languages import helpers\nfrom pre_commit.prefix import Prefix\nfrom pre_commit.util import CalledProcessError\nfrom pre_commit.util import clean_path_on_failure\nfrom pre_commit.util import cmd_output_b\n\nENVIRONMENT_DIR = 'docker'\nPRE_COMMIT_LABEL = 'PRE_COMMIT'\nget_default_version = helpers.basic_get_default_version\nhealthy = helpers.basic_healthy\n\n\ndef _is_in_docker() -> bool:\n    try:\n        with open('/proc/1/cgroup', 'rb') as f:\n            return b'docker' in f.read()\n    except FileNotFoundError:\n        return False\n\n\ndef _get_container_id() -> str:\n    # It's assumed that we already check /proc/1/cgroup in _is_in_docker. The\n    # cpuset cgroup controller existed since cgroups were introduced so this\n    # way of getting the container ID is pretty reliable.\n    with open('/proc/1/cgroup', 'rb') as f:\n        for line in f.readlines():\n            if line.split(b':')[1] == b'cpuset':\n                return os.path.basename(line.split(b':')[2]).strip().decode()\n    raise RuntimeError('Failed to find the container ID in /proc/1/cgroup.')\n\n\ndef _get_docker_path(path: str) -> str:\n    if not _is_in_docker():\n        return path\n\n    container_id = _get_container_id()\n\n    try:\n        _, out, _ = cmd_output_b('docker', 'inspect', container_id)\n    except CalledProcessError:\n        # self-container was not visible from here (perhaps docker-in-docker)\n        return path\n\n    container, = json.loads(out)\n    for mount in container['Mounts']:\n        src_path = mount['Source']\n        to_path = mount['Destination']\n        if os.path.commonpath((path, to_path)) == to_path:\n            # So there is something in common,\n            # and we can proceed remapping it\n            return path.replace(to_path, src_path)\n    # we're in Docker, but the path is not mounted, cannot really do anything,\n    # so fall back to original path\n    return path\n\n\ndef md5(s: str) -> str:  # pragma: win32 no cover\n    return hashlib.md5(s.encode()).hexdigest()\n\n\ndef docker_tag(prefix: Prefix) -> str:  # pragma: win32 no cover\n    md5sum = md5(os.path.basename(prefix.prefix_dir)).lower()\n    return f'pre-commit-{md5sum}'\n\n\ndef build_docker_image(\n        prefix: Prefix,\n        *,\n        pull: bool,\n) -> None:  # pragma: win32 no cover\n    cmd: Tuple[str, ...] = (\n        'docker', 'build',\n        '--tag', docker_tag(prefix),\n        '--label', PRE_COMMIT_LABEL,\n    )\n    if pull:\n        cmd += ('--pull',)\n    # This must come last for old versions of docker.  See #477\n    cmd += ('.',)\n    helpers.run_setup_cmd(prefix, cmd)\n\n\ndef install_environment(\n        prefix: Prefix, version: str, additional_dependencies: Sequence[str],\n) -> None:  # pragma: win32 no cover\n    helpers.assert_version_default('docker', version)\n    helpers.assert_no_additional_deps('docker', additional_dependencies)\n\n    directory = prefix.path(\n        helpers.environment_dir(ENVIRONMENT_DIR, C.DEFAULT),\n    )\n\n    # Docker doesn't really have relevant disk environment, but pre-commit\n    # still needs to cleanup its state files on failure\n    with clean_path_on_failure(directory):\n        build_docker_image(prefix, pull=True)\n        os.mkdir(directory)\n\n\ndef get_docker_user() -> Tuple[str, ...]:  # pragma: win32 no cover\n    try:\n        return ('-u', f'{os.getuid()}:{os.getgid()}')\n    except AttributeError:\n        return ()\n\n\ndef docker_cmd() -> Tuple[str, ...]:  # pragma: win32 no cover\n    return (\n        'docker', 'run',\n        '--rm',\n        *get_docker_user(),\n        # https://docs.docker.com/engine/reference/commandline/run/#mount-volumes-from-container-volumes-from\n        # The `Z` option tells Docker to label the content with a private\n        # unshared label. Only the current container can use a private volume.\n        '-v', f'{_get_docker_path(os.getcwd())}:/src:rw,Z',\n        '--workdir', '/src',\n    )\n\n\ndef run_hook(\n        hook: Hook,\n        file_args: Sequence[str],\n        color: bool,\n) -> Tuple[int, bytes]:  # pragma: win32 no cover\n    # Rebuild the docker image in case it has gone missing, as many people do\n    # automated cleanup of docker images.\n    build_docker_image(hook.prefix, pull=False)\n\n    entry_exe, *cmd_rest = hook.cmd\n\n    entry_tag = ('--entrypoint', entry_exe, docker_tag(hook.prefix))\n    cmd = (*docker_cmd(), *entry_tag, *cmd_rest)\n    return helpers.run_xargs(hook, cmd, file_args, color=color)\n", "path": "pre_commit/languages/docker.py"}]}