2016-09-19 25 views
0

我想在Python 3中構建自己一條整潔的管道。我的問題,一切似乎都很好,詹金斯總是給我一個綠色的泡泡,但有時候碼頭構建無法執行。如果構建失敗docker-py:我如何檢查構建是否成功?

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不會引發錯誤。

有人可以幫我找到正確的方法,我怎麼能確定我的構建完成,如果沒有得到一個有效的消息?我完全迷失了。

此致 的Mirco

回答

2

client.build返回發出docker build命令時由docker輸出的消息。您最初的錯誤是不捕獲響應:

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, [email protected] 
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'] 

正如您所看到的,包含errorDetailkey包含錯誤消息。

所以,你可以檢查的是,無論是用字節的字符串搜索:

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 

,或者甚至更好,通過將每個條目的dictast.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 
+0

我還沒試過,但至今非常感謝你的解釋如此之好。 –