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

时间:2016-09-19 14:45:10

标签: 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
如果构建失败,

不会引发错误。

有人可以帮我找到正确的方法,我如何确定我的构建已完成,如果没有获得有效的消息?我完全迷失了。

祝你好运 的Mirco

1 个答案:

答案 0 :(得分:2)

发出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']

如您所见,包含key errorDetail包含错误消息。

因此,您可以使用字节字符串搜索来检查:

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
相关问题