prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  When worker/master image creation failed, client should fail instead of trying to launch master.
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `elasticdl/client/client.py`
  Content:
  ```
  1 import argparse
  2 import os
  3 import inspect
  4 import tempfile
  5 import time
  6 import getpass
  7 import sys
  8 from string import Template
  9 import docker
  10 import yaml
  11 from kubernetes.client.apis import core_v1_api
  12 from kubernetes import config
  13 
  14 
  15 def _m_file_in_docker(model_file):
  16     return "/model/" + os.path.basename(model_file)
  17 
  18 def _build_docker_image(
  19     m_file, image_name, image_base="elasticdl:dev",
  20     repository=None
  21 ):
  22     DOCKER_TEMPLATE = """
  23 FROM {}
  24 COPY {} {}
  25 """
  26 
  27     with tempfile.NamedTemporaryFile(mode="w+", delete=False) as df:
  28         df.write(DOCKER_TEMPLATE.format(image_base, m_file, _m_file_in_docker(m_file)))
  29 
  30     client = docker.APIClient(base_url="unix://var/run/docker.sock")
  31     print("===== Building Docker Image =====")
  32     for line in client.build(
  33         dockerfile=df.name, path=".", rm=True, tag=image_name, decode=True
  34     ):
  35         text = line.get("stream", None)
  36         if text:
  37             sys.stdout.write(text)
  38             sys.stdout.flush()
  39     print("===== Docker Image Built =====")
  40     if repository != None:
  41         for line in client.push(image_name, stream=True, decode=True):
  42             print(line)
  43 
  44 def _gen_master_def(image_name, model_file, job_name, argv):
  45     master_yaml = """
  46 apiVersion: v1
  47 kind: Pod
  48 metadata:
  49   name: "elasticdl-master-{job_name}"
  50   labels:
  51     purpose: test-command
  52 spec:
  53   containers:
  54   - name: "elasticdl-master-{job_name}"
  55     image: "{image_name}"
  56     command: ["python"]
  57     args: [
  58         "-m", "elasticdl.master.main",
  59         "--job_name", "{job_name}",
  60         "--worker_image", "{image_name}",
  61         "--model_file", "{m_file}"
  62     ]
  63     imagePullPolicy: IfNotPresent 
  64     env:
  65     - name: MY_POD_IP
  66       valueFrom:
  67         fieldRef:
  68           fieldPath: status.podIP
  69   restartPolicy: Never
  70 """ .format(m_file=_m_file_in_docker(model_file), image_name=image_name, job_name=job_name)
  71 
  72     master_def = yaml.safe_load(master_yaml)
  73 
  74     # Build master arguments
  75     master_def['spec']['containers'][0]['args'].extend(argv)
  76     return master_def
  77 
  78 def _submit(image_name, model_file, job_name, argv):
  79     master_def = _gen_master_def(image_name, model_file, job_name, argv)
  80     config.load_kube_config()
  81     api = core_v1_api.CoreV1Api()
  82     resp = api.create_namespaced_pod(body=master_def, namespace="default")
  83     print("Master launched. status='%s'" % str(resp.status))
  84 
  85 def main():
  86     parser = argparse.ArgumentParser(description="ElasticDL Client")
  87     # Rewrite model_file argument and pass all other arguments to master.
  88     parser.add_argument("--model_file", help="Path to Model file", required=True)
  89     parser.add_argument("--image_base", help="Base image containing elasticdl runtime environment.", required=True)
  90     parser.add_argument("--repository", help="The repository to push docker image to.")
  91     parser.add_argument("--job_name", help="ElasticDL job name", required=True)
  92     args, argv = parser.parse_known_args()
  93 
  94     job_name = args.job_name + "-" + str(int(round(time.time() * 1000)))
  95     image_name = args.image_base + '_' + job_name 
  96     _build_docker_image(args.model_file, image_name, image_base=args.image_base,
  97         repository=args.repository)
  98     _submit(image_name, args.model_file, job_name, argv)
  99 
  100 
  101 if __name__ == "__main__":
  102     main()
  103
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/elasticdl/client/client.py b/elasticdl/client/client.py
  --- a/elasticdl/client/client.py
  +++ b/elasticdl/client/client.py
  @@ -32,12 +32,14 @@
       for line in client.build(
           dockerfile=df.name, path=".", rm=True, tag=image_name, decode=True
       ):
  +        if "error" in line:
  +            raise RuntimeError("Docker image build failure: " % line["error"])
           text = line.get("stream", None)
           if text:
               sys.stdout.write(text)
               sys.stdout.flush()
       print("===== Docker Image Built =====")
  -    if repository != None:
  +    if repository is not None:
           for line in client.push(image_name, stream=True, decode=True):
               print(line)
  
verification_info: {"golden_diff": "diff --git a/elasticdl/client/client.py b/elasticdl/client/client.py\n--- a/elasticdl/client/client.py\n+++ b/elasticdl/client/client.py\n@@ -32,12 +32,14 @@\n     for line in client.build(\n         dockerfile=df.name, path=\".\", rm=True, tag=image_name, decode=True\n     ):\n+        if \"error\" in line:\n+            raise RuntimeError(\"Docker image build failure: \" % line[\"error\"])\n         text = line.get(\"stream\", None)\n         if text:\n             sys.stdout.write(text)\n             sys.stdout.flush()\n     print(\"===== Docker Image Built =====\")\n-    if repository != None:\n+    if repository is not None:\n         for line in client.push(image_name, stream=True, decode=True):\n             print(line)\n", "issue": "When worker/master image creation failed, client should fail instead of trying to launch master.\n\n", "before_files": [{"content": "import argparse\nimport os\nimport inspect\nimport tempfile\nimport time\nimport getpass\nimport sys\nfrom string import Template\nimport docker\nimport yaml\nfrom kubernetes.client.apis import core_v1_api\nfrom kubernetes import config\n\n\ndef _m_file_in_docker(model_file):\n    return \"/model/\" + os.path.basename(model_file)\n\ndef _build_docker_image(\n    m_file, image_name, image_base=\"elasticdl:dev\",\n    repository=None\n):\n    DOCKER_TEMPLATE = \"\"\"\nFROM {}\nCOPY {} {}\n\"\"\"\n\n    with tempfile.NamedTemporaryFile(mode=\"w+\", delete=False) as df:\n        df.write(DOCKER_TEMPLATE.format(image_base, m_file, _m_file_in_docker(m_file)))\n\n    client = docker.APIClient(base_url=\"unix://var/run/docker.sock\")\n    print(\"===== Building Docker Image =====\")\n    for line in client.build(\n        dockerfile=df.name, path=\".\", rm=True, tag=image_name, decode=True\n    ):\n        text = line.get(\"stream\", None)\n        if text:\n            sys.stdout.write(text)\n            sys.stdout.flush()\n    print(\"===== Docker Image Built =====\")\n    if repository != None:\n        for line in client.push(image_name, stream=True, decode=True):\n            print(line)\n\ndef _gen_master_def(image_name, model_file, job_name, argv):\n    master_yaml = \"\"\"\napiVersion: v1\nkind: Pod\nmetadata:\n  name: \"elasticdl-master-{job_name}\"\n  labels:\n    purpose: test-command\nspec:\n  containers:\n  - name: \"elasticdl-master-{job_name}\"\n    image: \"{image_name}\"\n    command: [\"python\"]\n    args: [\n        \"-m\", \"elasticdl.master.main\",\n        \"--job_name\", \"{job_name}\",\n        \"--worker_image\", \"{image_name}\",\n        \"--model_file\", \"{m_file}\"\n    ]\n    imagePullPolicy: IfNotPresent \n    env:\n    - name: MY_POD_IP\n      valueFrom:\n        fieldRef:\n          fieldPath: status.podIP\n  restartPolicy: Never\n\"\"\" .format(m_file=_m_file_in_docker(model_file), image_name=image_name, job_name=job_name)\n\n    master_def = yaml.safe_load(master_yaml)\n\n    # Build master arguments\n    master_def['spec']['containers'][0]['args'].extend(argv)\n    return master_def\n\ndef _submit(image_name, model_file, job_name, argv):\n    master_def = _gen_master_def(image_name, model_file, job_name, argv)\n    config.load_kube_config()\n    api = core_v1_api.CoreV1Api()\n    resp = api.create_namespaced_pod(body=master_def, namespace=\"default\")\n    print(\"Master launched. status='%s'\" % str(resp.status))\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"ElasticDL Client\")\n    # Rewrite model_file argument and pass all other arguments to master.\n    parser.add_argument(\"--model_file\", help=\"Path to Model file\", required=True)\n    parser.add_argument(\"--image_base\", help=\"Base image containing elasticdl runtime environment.\", required=True)\n    parser.add_argument(\"--repository\", help=\"The repository to push docker image to.\")\n    parser.add_argument(\"--job_name\", help=\"ElasticDL job name\", required=True)\n    args, argv = parser.parse_known_args()\n\n    job_name = args.job_name + \"-\" + str(int(round(time.time() * 1000)))\n    image_name = args.image_base + '_' + job_name \n    _build_docker_image(args.model_file, image_name, image_base=args.image_base,\n        repository=args.repository)\n    _submit(image_name, args.model_file, job_name, argv)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "elasticdl/client/client.py"}], "after_files": [{"content": "import argparse\nimport os\nimport inspect\nimport tempfile\nimport time\nimport getpass\nimport sys\nfrom string import Template\nimport docker\nimport yaml\nfrom kubernetes.client.apis import core_v1_api\nfrom kubernetes import config\n\n\ndef _m_file_in_docker(model_file):\n    return \"/model/\" + os.path.basename(model_file)\n\ndef _build_docker_image(\n    m_file, image_name, image_base=\"elasticdl:dev\",\n    repository=None\n):\n    DOCKER_TEMPLATE = \"\"\"\nFROM {}\nCOPY {} {}\n\"\"\"\n\n    with tempfile.NamedTemporaryFile(mode=\"w+\", delete=False) as df:\n        df.write(DOCKER_TEMPLATE.format(image_base, m_file, _m_file_in_docker(m_file)))\n\n    client = docker.APIClient(base_url=\"unix://var/run/docker.sock\")\n    print(\"===== Building Docker Image =====\")\n    for line in client.build(\n        dockerfile=df.name, path=\".\", rm=True, tag=image_name, decode=True\n    ):\n        if \"error\" in line:\n            raise RuntimeError(\"Docker image build failure: \" % line[\"error\"])\n        text = line.get(\"stream\", None)\n        if text:\n            sys.stdout.write(text)\n            sys.stdout.flush()\n    print(\"===== Docker Image Built =====\")\n    if repository is not None:\n        for line in client.push(image_name, stream=True, decode=True):\n            print(line)\n\ndef _gen_master_def(image_name, model_file, job_name, argv):\n    master_yaml = \"\"\"\napiVersion: v1\nkind: Pod\nmetadata:\n  name: \"elasticdl-master-{job_name}\"\n  labels:\n    purpose: test-command\nspec:\n  containers:\n  - name: \"elasticdl-master-{job_name}\"\n    image: \"{image_name}\"\n    command: [\"python\"]\n    args: [\n        \"-m\", \"elasticdl.master.main\",\n        \"--job_name\", \"{job_name}\",\n        \"--worker_image\", \"{image_name}\",\n        \"--model_file\", \"{m_file}\"\n    ]\n    imagePullPolicy: IfNotPresent \n    env:\n    - name: MY_POD_IP\n      valueFrom:\n        fieldRef:\n          fieldPath: status.podIP\n  restartPolicy: Never\n\"\"\" .format(m_file=_m_file_in_docker(model_file), image_name=image_name, job_name=job_name)\n\n    master_def = yaml.safe_load(master_yaml)\n\n    # Build master arguments\n    master_def['spec']['containers'][0]['args'].extend(argv)\n    return master_def\n\ndef _submit(image_name, model_file, job_name, argv):\n    master_def = _gen_master_def(image_name, model_file, job_name, argv)\n    config.load_kube_config()\n    api = core_v1_api.CoreV1Api()\n    resp = api.create_namespaced_pod(body=master_def, namespace=\"default\")\n    print(\"Master launched. status='%s'\" % str(resp.status))\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"ElasticDL Client\")\n    # Rewrite model_file argument and pass all other arguments to master.\n    parser.add_argument(\"--model_file\", help=\"Path to Model file\", required=True)\n    parser.add_argument(\"--image_base\", help=\"Base image containing elasticdl runtime environment.\", required=True)\n    parser.add_argument(\"--repository\", help=\"The repository to push docker image to.\")\n    parser.add_argument(\"--job_name\", help=\"ElasticDL job name\", required=True)\n    args, argv = parser.parse_known_args()\n\n    job_name = args.job_name + \"-\" + str(int(round(time.time() * 1000)))\n    image_name = args.image_base + '_' + job_name \n    _build_docker_image(args.model_file, image_name, image_base=args.image_base,\n        repository=args.repository)\n    _submit(image_name, args.model_file, job_name, argv)\n\n\nif __name__ == \"__main__\":\n    main()\n", "path": "elasticdl/client/client.py"}]}