簡體   English   中英

docker-py:如何檢查構建是否成功?

[英]docker-py: how can I check if the build was successful?

我正在嘗試在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

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

如您所見,其中包含包含錯誤消息的errorDetail key

因此,您可以通過字節字符串搜索來進行檢查:

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將每個條目轉換為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM