首页 > 解决方案 > 如果需要多个标准输入,python asyncio 会死锁

问题描述

我编写了一个命令行工具来git pull使用 python asyncio 执行多个 git repos。如果所有存储库都具有 ssh 无密码登录设置,则它工作正常。如果只有 1 个 repo 需要输入密码,它也可以正常工作。当多个 repos 需要输入密码时,它似乎会陷入僵局。

我的实现非常简单。主要逻辑是

utils.exec_async_tasks(
        utils.run_async(path, cmds) for path in repos.values())

whererun_async创建并等待子进程调用,并exec_async_tasks运行所有任务。

async def run_async(path: str, cmds: List[str]):
    """
    Run `cmds` asynchronously in `path` directory
    """
    process = await asyncio.create_subprocess_exec(
        *cmds, stdout=asyncio.subprocess.PIPE, cwd=path)
    stdout, _ = await process.communicate()
    stdout and print(stdout.decode())


def exec_async_tasks(tasks: List[Coroutine]):
    """
    Execute tasks asynchronously
    """
    # TODO: asyncio API is nicer in python 3.7
    if platform.system() == 'Windows':
        loop = asyncio.ProactorEventLoop()
        asyncio.set_event_loop(loop)
    else:
        loop = asyncio.get_event_loop()

    try:
        loop.run_until_complete(asyncio.gather(*tasks))
    finally:
        loop.close()

完整的代码库在 github 上

我认为问题类似于以下内容。在run_async,asyncio.create_subprocess_exec中,stdin 没有重定向,系统的 stdin 用于所有子进程(repos)。当第一个 repo 要求输入密码时,asyncio 调度程序看到一个阻塞输入,并在等待命令行输入时切换到第二个 repo。但是如果第二个仓库在第一个仓库的密码输入完成之前要求输入密码,系统的标准输入将链接到第二个仓库。第一个 repo 将永远等待输入。

我不知道如何处理这种情况。我必须为每个子进程重定向标准输入吗?如果有些 repos 有无密码登录而有些没有怎么办?

一些想法如下

  1. 检测何时需要输入密码create_subprocess_exec。如果是,则调用input()并将其结果传递给process.communicate(input). 但是我怎样才能即时检测到呢?

  2. 检测哪些 repos 需要输入密码,并将它们从异步执行中排除。最好的方法是什么?

标签: pythongitsubprocessstdinpython-asyncio

解决方案


在默认配置中,当需要用户名或密码时,git直接访问/dev/tty同义词以更好地控制“控制”终端设备,例如让您与用户交互的设备。由于默认情况下子进程从其父进程继承控制终端,因此您启动的所有 git 进程都将访问同一个 TTY 设备。所以是的,当尝试读取和写入同一个 TTY 时,它们会挂起,进程会破坏彼此的预期输入。

防止这种情况发生的一种简单方法是为每个子进程提供自己的会话;不同的会话每个都有不同的控制 TTY。通过设置start_new_session=True

process = await asyncio.create_subprocess_exec(
    *cmds, stdout=asyncio.subprocess.PIPE, cwd=path, start_new_session=True)

您无法真正预先确定哪些 git 命令可能需要用户凭据,因为 git 可以配置为从整个位置获取凭据,并且这些仅在远程存储库实际挑战身份验证时使用。

更糟糕的是,对于ssh://远程 URL,git 根本不处理身份验证,而是将其留给ssh它打开的客户端进程。更多关于下面的内容。

然而, Git 如何请求凭据(除 之外的任何内容ssh)是可配置的;请参阅gitcredentials 文档。如果您的代码必须能够将凭据请求转发给最终用户,则可以使用此功能。我不会让 git 命令通过终端执行此操作,因为用户将如何知道哪个特定的 git 命令将接收哪些凭据,更不用说确保提示到达时遇到的问题了逻辑顺序。

相反,我会通过您的脚本路由所有对凭据的请求。您有两种选择:

  • 设置GIT_ASKPASS环境变量,指向 git 应该为每个提示运行的可执行文件。

    使用单个参数调用此可执行文件,即向用户显示的提示。对于给定凭证所需的每条信息,它会单独调用,因此对于用户名(如果还不知道)和密码也是如此。提示文本应该让用户清楚地知道所要求的内容(例如"Username for 'https://github.com': ",或"Password for 'https://someusername@github.com': ".

  • 注册一个凭证助手;这是作为一个 shell 命令执行的(因此可以有自己的预配置命令行参数),还有一个额外的参数告诉助手它需要什么样的操作。如果它get作为最后一个参数传递,那么它被要求提供给定主机和协议的凭据,或者可以告诉它某些凭据是成功的store,或者被拒绝了erase。在所有情况下,它都可以从标准输入读取信息,以了解主机 git 试图以多行key=value格式进行身份验证的对象。

    因此,使用凭证助手,您可以一步提示输入用户名和密码组合,并且您还可以获得有关该过程的更多信息;处理storeerase操作使您可以更有效地缓存凭据。

Git fill 首先按配置顺序询问每个配置的凭证助手(请参阅FILES了解如何按顺序处理 4 个配置文件位置的部分)。您可以使用添加到末尾git的命令行开关在命令行上添加新的一次性助手配置。-c credential.helper=...如果没有凭证助手能够填写缺少的用户名或密码,则系统会提示用户GIT_ASKPASS其他提示选项

对于 SSH 连接,git 创建一个新的ssh子进程。然后 SSH 将处理身份验证,并可以向用户询问凭据,或者对于 ssh 密钥,向用户询问密码。这将再次通过 完成/dev/tty,而 SSH 对此更加固执。虽然您可以将SSH_ASKPASS环境变量设置为用于提示的二进制文件,但 SSH 仅在没有 TTY 会话并且DISPLAY也设置为时才使用它。

SSH_ASKPASS必须是可执行文件(因此不传递参数),并且您不会收到提示凭据成功或失败的通知。

我还要确保将当前环境变量复制到子进程,因为如果用户设置了 SSH 密钥代理来缓存 ssh 密钥,那么您会希望 git 开始使用它们的 SSH 进程;通过环境变量发现关键代理。

因此,要为凭证助手创建连接,并且也适用于SSH_ASKPASS,您可以使用一个简单的同步脚本,该脚本从环境变量中获取套接字:

#!/path/to/python3
import os, socket, sys
path = os.environ['PROMPTING_SOCKET_PATH']
operation = sys.argv[1]
if operation not in {'get', 'store', 'erase'}:
    operation, params = 'prompt', f'prompt={operation}\n'
else:
    params = sys.stdin.read()
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
    s.connect(path)
    s.sendall(f'''operation={operation}\n{params}'''.encode())
    print(s.recv(2048).decode())

这应该设置了可执行位。

然后可以将其作为临时文件传递给 git 命令或包含在预构建文件中,然后在PROMPTING_SOCKET_PATH环境变量中添加 Unix 域套接字路径。它可以SSH_ASKPASS兼作提示器,将操作设置为prompt

然后,此脚本使 SSH 和 git 在每个用户的单独连接中向您的 UNIX 域套接字服务器询问用户凭据。我使用了很大的接收缓冲区大小,我认为您永远不会遇到与此协议的交换会超过它,我也看不出它有任何不足的理由。它使脚本保持美观和简单。

您可以改为将其用作GIT_ASKPASS命令,但是您不会获得有关非 ssh 连接凭据成功的有价值信息。

这是一个 UNIX 域套接字服务器的演示实现,它处理来自上述凭证助手的 git 和凭证请求,它只生成随机十六进制值而不是询问用户:

import asyncio
import os
import secrets
import tempfile

async def handle_git_prompt(reader, writer):
    data = await reader.read(2048)
    info = dict(line.split('=', 1) for line in data.decode().splitlines())
    print(f"Received credentials request: {info!r}")

    response = []
    operation = info.pop('operation', 'get')

    if operation == 'prompt':
        # new prompt for a username or password or pass phrase for SSH
        password = secrets.token_hex(10)
        print(f"Sending prompt response: {password!r}")
        response.append(password)

    elif operation == 'get':
        # new request for credentials, for a username (optional) and password
        if 'username' not in info:
            username = secrets.token_hex(10)
            print(f"Sending username: {username!r}")
            response.append(f'username={username}\n')

        password = secrets.token_hex(10)
        print(f"Sending password: {password!r}")
        response.append(f'password={password}\n')

    elif operation == 'store':
        # credentials were used successfully, perhaps store these for re-use
        print(f"Credentials for {info['username']} were approved")

    elif operation == 'erase':
        # credentials were rejected, if we cached anything, clear this now.
        print(f"Credentials for {info['username']} were rejected")

    writer.write(''.join(response).encode())
    await writer.drain()

    print("Closing the connection")
    writer.close()
    await writer.wait_closed()

async def main():
    with tempfile.TemporaryDirectory() as dirname:
        socket_path = os.path.join(dirname, 'credential.helper.sock')
        server = await asyncio.start_unix_server(handle_git_prompt, socket_path)

        print(f'Starting a domain socket at {server.sockets[0].getsockname()}')

        async with server:
            await server.serve_forever()

asyncio.run(main())

请注意,凭证助手也可以在输出中添加quit=truequit=1告诉 git 不要寻找任何其他凭证助手并且不再提示。

您可以使用该git credential <operation>命令测试凭证助手是否有效,方法是/full/path/to/credhelper.py使用 git-c credential.helper=...命令行选项传入助手脚本 ( )。git credential可以url=...在标准输入上接受一个字符串,它会像 git 联系凭证助手一样解析它;请参阅文档以获取完整的交换格式规范。

首先,在单独的终端中启动上述演示脚本:

$ /usr/local/bin/python3.7 git-credentials-demo.py
Starting a domain socket at /tmp/credhelper.py /var/folders/vh/80414gbd6p1cs28cfjtql3l80000gn/T/tmprxgyvecj/credential.helper.sock

然后尝试从中获取凭据;我还包括了storeanderase操作的演示:

$ export PROMPTING_SOCKET_PATH="/var/folders/vh/80414gbd6p1cs28cfjtql3l80000gn/T/tmprxgyvecj/credential.helper.sock"
$ CREDHELPER="/tmp/credhelper.py"
$ echo "url=https://example.com:4242/some/path.git" | git -c "credential.helper=$CREDHELPER" credential fill
protocol=https
host=example.com:4242
username=5b5b0b9609c1a4f94119
password=e259f5be2c96fed718e6
$ echo "url=https://someuser@example.com/some/path.git" | git -c "credential.helper=$CREDHELPER" credential fill
protocol=https
host=example.com
username=someuser
password=766df0fba1de153c3e99
$ printf "protocol=https\nhost=example.com:4242\nusername=5b5b0b9609c1a4f94119\npassword=e259f5be2c96fed718e6" | git -c "credential.helper=$CREDHELPER" credential approve
$ printf "protocol=https\nhost=example.com\nusername=someuser\npassword=e259f5be2c96fed718e6" | git -c "credential.helper=$CREDHELPER" credential reject

然后当您查看示例脚本的输出时,您会看到:

Received credentials request: {'operation': 'get', 'protocol': 'https', 'host': 'example.com:4242'}
Sending username: '5b5b0b9609c1a4f94119'
Sending password: 'e259f5be2c96fed718e6'
Closing the connection
Received credentials request: {'operation': 'get', 'protocol': 'https', 'host': 'example.com', 'username': 'someuser'}
Sending password: '766df0fba1de153c3e99'
Closing the connection
Received credentials request: {'operation': 'store', 'protocol': 'https', 'host': 'example.com:4242', 'username': '5b5b0b9609c1a4f94119', 'password': 'e259f5be2c96fed718e6'}
Credentials for 5b5b0b9609c1a4f94119 were approved
Closing the connection
Received credentials request: {'operation': 'erase', 'protocol': 'https', 'host': 'example.com', 'username': 'someuser', 'password': 'e259f5be2c96fed718e6'}
Credentials for someuser were rejected
Closing the connection

注意帮助器是如何被赋予一组解析出来的字段的, forprotocolhost,并且省略了路径;如果您设置了 git config 选项credential.useHttpPath=true(或者已经为您设置了),那么path=some/path.git将被添加到正在传递的信息中。

对于 SSH,可执行文件只需调用一个提示即可显示:

$ $CREDHELPER "Please enter a super-secret passphrase: "
30b5978210f46bb968b2

并且演示服务器已打印:

Received credentials request: {'operation': 'prompt', 'prompt': 'Please enter a super-secret passphrase: '}
Sending prompt response: '30b5978210f46bb968b2'
Closing the connection

只需确保start_new_session=True在启动 git 进程时仍然设置,以确保强制使用 SSH SSH_ASKPASS

env = {
    os.environ,
    SSH_ASKPASS='../path/to/credhelper.py',
    DISPLAY='dummy value',
    PROMPTING_SOCKET_PATH='../path/to/domain/socket',
}
process = await asyncio.create_subprocess_exec(
    *cmds, stdout=asyncio.subprocess.PIPE, cwd=path, 
    start_new_session=True, env=env)

当然,如何处理提示用户是一个单独的问题,但您的脚本现在拥有完全控制权(每个git命令将耐心等待凭证助手返回请求的信息),您可以将请求排队等待用户填写,并且您可以根据需要缓存凭据(以防多个命令都在等待同一主机的凭据)。


推荐阅读