Browse Source

Merge pull request #8038 from unclejack/failed_build_context_cleanup

clean up the context when a build fails
Alexandr Morozov 10 years ago
parent
commit
88a786d3c4
2 changed files with 31 additions and 4 deletions
  1. 6 4
      builder/evaluator.go
  2. 25 0
      integration-cli/docker_cli_build_test.go

+ 6 - 4
builder/evaluator.go

@@ -119,6 +119,12 @@ func (b *Builder) Run(context io.Reader) (string, error) {
 		return "", err
 	}
 
+	defer func() {
+		if err := os.RemoveAll(b.contextPath); err != nil {
+			log.Debugf("[BUILDER] failed to remove temporary context: %s", err)
+		}
+	}()
+
 	filename := path.Join(b.contextPath, "Dockerfile")
 
 	fi, err := os.Stat(filename)
@@ -164,10 +170,6 @@ func (b *Builder) Run(context io.Reader) (string, error) {
 		return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?\n")
 	}
 
-	if err := os.RemoveAll(b.contextPath); err != nil {
-		log.Debugf("[BUILDER] failed to remove temporary context: %s", err)
-	}
-
 	fmt.Fprintf(b.OutStream, "Successfully built %s\n", utils.TruncateID(b.image))
 	return b.image, nil
 }

+ 25 - 0
integration-cli/docker_cli_build_test.go

@@ -731,6 +731,31 @@ func TestBuildContextCleanup(t *testing.T) {
 	logDone("build - verify context cleanup works properly")
 }
 
+func TestBuildContextCleanupFailedBuild(t *testing.T) {
+	name := "testbuildcontextcleanup"
+	defer deleteImages(name)
+	entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
+	if err != nil {
+		t.Fatalf("failed to list contents of tmp dir: %s", err)
+	}
+	_, err = buildImage(name,
+		`FROM scratch
+	RUN /non/existing/command`,
+		true)
+	if err == nil {
+		t.Fatalf("expected build to fail, but it didn't")
+	}
+	entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
+	if err != nil {
+		t.Fatalf("failed to list contents of tmp dir: %s", err)
+	}
+	if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
+		t.Fatalf("context should have been deleted, but wasn't")
+	}
+
+	logDone("build - verify context cleanup works properly after a failed build")
+}
+
 func TestBuildCmd(t *testing.T) {
 	name := "testbuildcmd"
 	expected := "[/bin/echo Hello World]"