Skip to content

Commit 5f70b23

Browse files
samuelkarpthaJeztah
authored andcommitted
shim: WritePidFile & WriteAddress use atomicfile
Signed-off-by: Samuel Karp <[email protected]> (cherry picked from commit c409c63) Signed-off-by: Sebastiaan van Stijn <[email protected]>
1 parent 505d444 commit 5f70b23

1 file changed

Lines changed: 10 additions & 10 deletions

File tree

runtime/v2/shim/util.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,13 @@ import (
2727
"strings"
2828
"time"
2929

30-
"github.com/containerd/containerd/namespaces"
3130
"github.com/containerd/ttrpc"
3231
"github.com/gogo/protobuf/proto"
3332
"github.com/gogo/protobuf/types"
3433
exec "golang.org/x/sys/execabs"
34+
35+
"github.com/containerd/containerd/namespaces"
36+
"github.com/containerd/containerd/pkg/atomicfile"
3537
)
3638

3739
type CommandConfig struct {
@@ -118,17 +120,16 @@ func WritePidFile(path string, pid int) error {
118120
if err != nil {
119121
return err
120122
}
121-
tempPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path)))
122-
f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
123+
f, err := atomicfile.New(path, 0o666)
123124
if err != nil {
124125
return err
125126
}
126127
_, err = fmt.Fprintf(f, "%d", pid)
127-
f.Close()
128128
if err != nil {
129+
f.Cancel()
129130
return err
130131
}
131-
return os.Rename(tempPath, path)
132+
return f.Close()
132133
}
133134

134135
// WriteAddress writes a address file atomically
@@ -137,17 +138,16 @@ func WriteAddress(path, address string) error {
137138
if err != nil {
138139
return err
139140
}
140-
tempPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path)))
141-
f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
141+
f, err := atomicfile.New(path, 0o666)
142142
if err != nil {
143143
return err
144144
}
145-
_, err = f.WriteString(address)
146-
f.Close()
145+
_, err = f.Write([]byte(address))
147146
if err != nil {
147+
f.Cancel()
148148
return err
149149
}
150-
return os.Rename(tempPath, path)
150+
return f.Close()
151151
}
152152

153153
// ErrNoAddress is returned when the address file has no content

0 commit comments

Comments
 (0)