From 03478d4540789b4e4c9a79c7421121cd22371306 Mon Sep 17 00:00:00 2001 From: Ted Yu Date: Thu, 21 Nov 2019 02:27:17 -0800 Subject: [PATCH] vc: Clean up directories in case MkdirAll fails Fixes #2230 Signed-off-by: Ted Yu --- virtcontainers/persist/fs/fs.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/virtcontainers/persist/fs/fs.go b/virtcontainers/persist/fs/fs.go index 0b4f28bc02..1322e53d49 100644 --- a/virtcontainers/persist/fs/fs.go +++ b/virtcontainers/persist/fs/fs.go @@ -126,12 +126,22 @@ func (fs *FS) ToDisk(ss persistapi.SandboxState, cs map[string]persistapi.Contai return err } + var dirCreationErr error + var createdDirs []string + defer func() { + if dirCreationErr != nil && len(createdDirs) > 0 { + for _, dir := range createdDirs { + os.RemoveAll(dir) + } + } + }() // persist container configuration data for cid, cstate := range fs.containerState { cdir := filepath.Join(sandboxDir, cid) - if err := os.MkdirAll(cdir, dirMode); err != nil { - return err + if dirCreationErr = os.MkdirAll(cdir, dirMode); dirCreationErr != nil { + return dirCreationErr } + createdDirs = append(createdDirs, cdir) cfile := filepath.Join(cdir, persistFile) cf, err := os.OpenFile(cfile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileMode)