Skip to content

Commit

Permalink
Hardening lifecycle state store
Browse files Browse the repository at this point in the history
Signed-off-by: apostasie <[email protected]>
  • Loading branch information
apostasie committed Aug 24, 2024
1 parent 04a9536 commit 0d828c9
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
7 changes: 3 additions & 4 deletions pkg/ocihook/ocihook.go
Original file line number Diff line number Diff line change
Expand Up @@ -514,10 +514,9 @@ func onCreateRuntime(opts *handlerOpts) error {
// Set StartedAt
lf := state.NewLifecycleState(opts.state.Annotations[labels.StateDir])
return lf.WithLock(func() error {
err := lf.Load()
if err != nil {
return err
}
// Errors are voluntarily ignored here, as they should not be fatal.
// The lifecycle struct is also already warning about the issue.
_ = lf.Load()
lf.StartedAt = time.Now()
return lf.Save()
})
Expand Down
12 changes: 11 additions & 1 deletion pkg/ocihook/state/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import (
"path/filepath"
"time"

"github.com/containerd/log"

"github.com/containerd/nerdctl/v2/pkg/lockutil"
)

Expand Down Expand Up @@ -71,18 +73,26 @@ func (lf *LifecycleState) Load() error {
} else {
err = json.Unmarshal(data, lf)
if err != nil {
backout := filepath.Join(lf.stateDir, lifecycleFile, ".bak")
log.L.Error("unable to unmarshall lifecycle data: %w - broken file has been moved to %q - you should"+

Check failure on line 77 in pkg/ocihook/state/state.go

View workflow job for this annotation

GitHub Actions / lint

printf: (*github.com/sirupsen/logrus.Entry).Error call has possible Printf formatting directive %q (govet)

Check failure on line 77 in pkg/ocihook/state/state.go

View workflow job for this annotation

GitHub Actions / test-unit

(*github.com/sirupsen/logrus.Entry).Error call has possible Printf formatting directive %q
"investigate manually and possibly report as a bug", err, backout)
return fmt.Errorf("unable to unmarshall lifecycle data: %w", err)
}
}
return nil
}

func (lf *LifecycleState) Save() error {
// Write atomically (write, then move) to avoid incomplete writes from happening
data, err := json.Marshal(lf)
if err != nil {
return fmt.Errorf("unable to marshall lifecycle data: %w", err)
}
err = os.WriteFile(filepath.Join(lf.stateDir, lifecycleFile), data, 0600)
err = os.WriteFile(filepath.Join(lf.stateDir, "."+lifecycleFile), data, 0600)
if err != nil {
return fmt.Errorf("unable to write lifecycle file: %w", err)
}
err = os.Rename(filepath.Join(lf.stateDir, "."+lifecycleFile), filepath.Join(lf.stateDir, lifecycleFile))
if err != nil {
return fmt.Errorf("unable to write lifecycle file: %w", err)
}
Expand Down

0 comments on commit 0d828c9

Please sign in to comment.