python - docker-py:如何检查构建是否成功?

标签 python python-3.x docker dockerpy

我正在尝试使用Python 3构建一个整洁的管道。我的问题是,一切似乎都正常运行,Jenkins总是给我带来一个绿色的泡沫,但有时docker build无法执行。

因此,如果由于某种原因构建中断,client.build不会引发错误:

try:
    self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag)
except:
     print("Error: Docker did not build)
     raise

如果构建失败,则不会引发错误。

有人可以帮助我找到正确的方法,如何确定构建完成以及是否未收到有效消息的帮助吗?我完全迷路了。

最好的祝福
米尔科

最佳答案

client.build返回发出docker命令时docker build输出的消息。您最初的错误是未捕获响应:

response = cl.build(fileobj=f, rm = True, tag='myv/v')

如果成功,则内容与通过命令行执行时的内容相同:
list(response)
b'{"stream":" ---\\u003e bb44cb7f2d89\\n"}\r\n',
# snipped for brevity
b'{"stream":"Successfully built 6bc18019ddb6\\n"}\r\n']

在错误情况下,例如,使用愚蠢的dockerfile:
# a dockerfile with a type in 'MAINTAINER'
f = BytesIO('''
# Shared Volume
FROM busybox:buildroot-2014.02
MAINTAIER first last, first.last@yourdomain.com
VOLUME /data
CMD ["/bin/sh"]
'''.encode('utf-8'))
response中包含的输出如下所示:
[b'{"stream":"Step 1 : FROM busybox:buildroot-2014.02\\n"}\r\n',
 b'{"stream":" ---\\u003e 9875fb006e07\\n"}\r\n',
 b'{"stream":"Step 2 : MAINTAIER \\n"}\r\n',
 b'{"errorDetail":{"message":"Unknown instruction: MAINTAIER"},"error":"Unknown instruction: MAINTAIER"}\r\n']

如您所见,其中包含错误消息的keyerrorDetail

因此,您可以使用字节字符串搜索进行检查:
class DockerBuildException(BaseException): pass 


try:
    responce = self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag)
    for i in respone:
        if b'errorDetail' in i:
             raise DockerBuildException("Build Failed")
except DockerBuildException as e:
     print("Error: " + e.args[0])
     raise

或者,甚至更好的是,通过使用dict将每个条目转换为ast.literal_eval并使用提供的消息来通知用户:
from ast import literal_eval

try:
    responce = self.client.build(path=self.arguments.projectPath, pull=True, rm=False, tag=self.arguments.dockerImageTag)
    for i in respone:
        if b'errorDetail' in i:
            d = literal_eval(i.decode('ascii')
            raise DockerBuildException(d['errorDetail']['message'])
except DockerBuildException as e:
     print("Error: " + e.args[0])
     raise

关于python - docker-py:如何检查构建是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39575982/

相关文章:

python - 椭圆化列表连接,Pythonically

python - 如何通过输入使变量包含字典中的字符串

python - 这个 for 循环如何处理以下字符串?

python - 如何更新 matplotlib 中 imshow 的范围?

python - 捕获异步流服务器中的异常

nginx - 带有粘性 session 的 docker-compose 规模

python-3.x - threading.Condition 和 threading.Event 之间的区别

python - 给定一个 Unicode 代码点列表,如何将它们拆分为 Unicode 字符列表?

docker - 如何在 Alpine 中以非 root 身份运行 Cron

docker - 添加rewrite_by_lua模块到nginx :alpine