From 2f4aedff8329c195cdf6f6ceab3ffe09739e5c96 Mon Sep 17 00:00:00 2001 From: Peter Hunt Date: Wed, 13 Apr 2022 13:24:57 -0400 Subject: [PATCH] oci: cleanup log path if the container failed to create Signed-off-by: Peter Hunt --- internal/oci/runtime_oci.go | 8 ++++++++ internal/oci/runtime_vm.go | 3 +++ test/ctr.bats | 15 +++++++++++++++ 3 files changed, 26 insertions(+) diff --git a/internal/oci/runtime_oci.go b/internal/oci/runtime_oci.go index 32a06ff3893..cdb679329ad 100644 --- a/internal/oci/runtime_oci.go +++ b/internal/oci/runtime_oci.go @@ -199,6 +199,14 @@ func (r *runtimeOCI) CreateContainer(ctx context.Context, c *Container, cgroupPa }(); err != nil { return err } + + defer func() { + if retErr != nil { + if err := os.Remove(c.logPath); err != nil { + log.Warnf(ctx, "Failed to remove log path %s after failing to create container: %v", c.logPath, err) + } + } + }() /* Wait for initial setup and fork, and reap child */ err = cmd.Wait() if err != nil { diff --git a/internal/oci/runtime_vm.go b/internal/oci/runtime_vm.go index 001328c61c0..15f197fd5ec 100644 --- a/internal/oci/runtime_vm.go +++ b/internal/oci/runtime_vm.go @@ -134,6 +134,9 @@ func (r *runtimeVM) CreateContainer(ctx context.Context, c *Container, cgroupPar if cleanupErr := r.deleteContainer(c, true); cleanupErr != nil { log.Infof(ctx, "DeleteContainer failed for container %s: %v", c.ID(), cleanupErr) } + if err := os.Remove(c.logPath); err != nil { + log.Warnf(ctx, "Failed to remove log path %s after failing to create container: %v", c.logPath, err) + } } }() diff --git a/test/ctr.bats b/test/ctr.bats index 6bfd8a68f92..796a2361dc3 100644 --- a/test/ctr.bats +++ b/test/ctr.bats @@ -171,6 +171,21 @@ function check_oci_annotation() { grep -E "^[^\n]+ stderr F and some from stderr$" "$logpath" } +@test "ctr log cleaned up if container create failed" { + start_crio + pod_id=$(crictl runp "$TESTDATA"/sandbox_config.json) + + # Create a new container. + jq ' .command = ["invalid"]' \ + "$TESTDATA"/container_config.json > "$newconfig" + ! crictl create "$pod_id" "$newconfig" "$TESTDATA"/sandbox_config.json + + # CRI-O should cleanup the log if the container failed to create + for file in "$DEFAULT_LOG_PATH/$pod_id"/*; do + [[ "$file" != "$pod_id" ]] + done +} + @test "ctr journald logging" { if ! check_journald; then skip "journald logging not supported"