Skip to content

Commit a3fdaaf

Browse files
author
baijia
committed
fix: cleanup volume dir if create volume failed
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 <[email protected]>
1 parent eb25c21 commit a3fdaaf

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

pkg/mountutil/volumestore/volumestore.go

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424

2525
"github.com/containerd/containerd/errdefs"
2626
"github.com/containerd/containerd/identifiers"
27+
"github.com/containerd/log"
2728
"github.com/containerd/nerdctl/v2/pkg/inspecttypes/native"
2829
"github.com/containerd/nerdctl/v2/pkg/lockutil"
2930
"github.com/containerd/nerdctl/v2/pkg/strutil"
@@ -83,13 +84,24 @@ func (vs *volumeStore) Create(name string, labels []string) (*native.Volume, err
8384
}
8485
volPath := filepath.Join(vs.dir, name)
8586
volDataPath := filepath.Join(volPath, DataDirName)
86-
fn := func() error {
87+
volFilePath := filepath.Join(volPath, volumeJSONFileName)
88+
fn := func() (err error) {
8789
if err := os.Mkdir(volPath, 0700); err != nil {
8890
return err
8991
}
92+
defer func() {
93+
if err != nil {
94+
os.Remove(volPath)
95+
}
96+
}()
9097
if err := os.Mkdir(volDataPath, 0755); err != nil {
9198
return err
9299
}
100+
defer func() {
101+
if err != nil {
102+
os.Remove(volDataPath)
103+
}
104+
}()
93105

94106
type volumeOpts struct {
95107
Labels map[string]string `json:"labels"`
@@ -106,14 +118,25 @@ func (vs *volumeStore) Create(name string, labels []string) (*native.Volume, err
106118
return err
107119
}
108120

109-
volFilePath := filepath.Join(volPath, volumeJSONFileName)
121+
defer func() {
122+
if err != nil {
123+
if _, statErr := os.Stat(volFilePath); statErr != nil && !os.IsNotExist(statErr) {
124+
log.L.Warnf("failed to stat volume file: %v", statErr)
125+
return
126+
} else if statErr == nil {
127+
os.Remove(volFilePath)
128+
}
129+
}
130+
}()
110131
return os.WriteFile(volFilePath, labelsJSON, 0644)
111132
}
112133

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

138+
// If other new actions that might fail are added below, we should move the cleanup function out of fn.
139+
117140
vol := &native.Volume{
118141
Name: name,
119142
Mountpoint: volDataPath,

0 commit comments

Comments
 (0)