Skip to content

Commit

Permalink
fix: cleanup volume dir if create volume failed
Browse files Browse the repository at this point in the history
Volume path should be cleaned up if create volume failed.
Otherwise, the same volume will be created failed again
next time with a 'file exists' error on os.Mkdir.

Signed-off-by: baijia <baijia.wr@antgroup.com>
  • Loading branch information
白加 committed Mar 19, 2024
1 parent faf83fc commit 22a9024
Showing 1 changed file with 21 additions and 2 deletions.
23 changes: 21 additions & 2 deletions pkg/mountutil/volumestore/volumestore.go
Expand Up @@ -24,6 +24,7 @@ import (

"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/identifiers"
"github.com/containerd/log"
"github.com/containerd/nerdctl/v2/pkg/inspecttypes/native"
"github.com/containerd/nerdctl/v2/pkg/lockutil"
"github.com/containerd/nerdctl/v2/pkg/strutil"
Expand Down Expand Up @@ -83,13 +84,30 @@ func (vs *volumeStore) Create(name string, labels []string) (*native.Volume, err
}
volPath := filepath.Join(vs.dir, name)
volDataPath := filepath.Join(volPath, DataDirName)
fn := func() error {
volFilePath := filepath.Join(volPath, volumeJSONFileName)
fn := func() (err error) {
if err := os.Mkdir(volPath, 0700); err != nil {
return err
}
defer func() {
if err != nil {
os.Remove(volPath)
}
}()
if err := os.Mkdir(volDataPath, 0755); err != nil {
return err
}
defer func() {
if err != nil {
if _, statErr := os.Stat(volFilePath); statErr != nil && !os.IsNotExist(statErr) {
log.L.Warnf("failed to stat volume file: %v", statErr)
return
} else if statErr == nil {
os.Remove(volFilePath)
}
os.Remove(volDataPath)
}
}()

type volumeOpts struct {
Labels map[string]string `json:"labels"`
Expand All @@ -106,14 +124,15 @@ func (vs *volumeStore) Create(name string, labels []string) (*native.Volume, err
return err
}

volFilePath := filepath.Join(volPath, volumeJSONFileName)
return os.WriteFile(volFilePath, labelsJSON, 0644)
}

if err := lockutil.WithDirLock(vs.dir, fn); err != nil {
return nil, err
}

// If other new actions that might fail are added below, we should move the cleanup function out of fn.

vol := &native.Volume{
Name: name,
Mountpoint: volDataPath,
Expand Down

0 comments on commit 22a9024

Please sign in to comment.