docker-py:如何检查构build是否成功?
我试图在Python 3中构build自己的pipe道。我的问题,似乎一切都很好,jenkins总是给我一个绿色的泡沫,但有时docker构build无法执行。
所以,如果构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
如果构build失败,不会引发错误。
有人可以帮助我find正确的方法,我怎么能确定我的构build完成,如果没有得到一个有效的消息? 我完全迷失了。
最好的问候Mirco
client.build
在发出client.build
docker build
命令时返回client.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']
正如你所看到的, errorDetail
的key
包含错误信息。
所以,你可以用stringsearch来检查:
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
或者,甚至更好的ast.literal_eval
是,将每个条目转换为带有ast.literal_eval
的dict
,并使用提供的消息通知用户:
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