shim: WritePidFile & WriteAddress use atomicfile

Signed-off-by: Samuel Karp <samuelkarp@google.com>
This commit is contained in:
Samuel Karp 2023-05-31 22:41:18 -07:00
parent 3c4a1ab1cb
commit c409c631ca
No known key found for this signature in database
GPG Key ID: 997C5A3CD3167CB5

View File

@ -28,13 +28,15 @@ import (
"strings" "strings"
"time" "time"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/protobuf/proto"
"github.com/containerd/containerd/protobuf/types"
"github.com/containerd/ttrpc" "github.com/containerd/ttrpc"
"github.com/containerd/typeurl/v2" "github.com/containerd/typeurl/v2"
exec "golang.org/x/sys/execabs" exec "golang.org/x/sys/execabs"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/pkg/atomicfile"
"github.com/containerd/containerd/protobuf/proto"
"github.com/containerd/containerd/protobuf/types"
) )
type CommandConfig struct { type CommandConfig struct {
@ -124,17 +126,16 @@ func WritePidFile(path string, pid int) error {
if err != nil { if err != nil {
return err return err
} }
tempPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path))) f, err := atomicfile.New(path, 0o666)
f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
if err != nil { if err != nil {
return err return err
} }
_, err = fmt.Fprintf(f, "%d", pid) _, err = fmt.Fprintf(f, "%d", pid)
f.Close()
if err != nil { if err != nil {
f.Cancel()
return err return err
} }
return os.Rename(tempPath, path) return f.Close()
} }
// WriteAddress writes a address file atomically // WriteAddress writes a address file atomically
@ -143,17 +144,16 @@ func WriteAddress(path, address string) error {
if err != nil { if err != nil {
return err return err
} }
tempPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path))) f, err := atomicfile.New(path, 0o666)
f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
if err != nil { if err != nil {
return err return err
} }
_, err = f.WriteString(address) _, err = f.Write([]byte(address))
f.Close()
if err != nil { if err != nil {
f.Cancel()
return err return err
} }
return os.Rename(tempPath, path) return f.Close()
} }
// ErrNoAddress is returned when the address file has no content // ErrNoAddress is returned when the address file has no content