File: safepath.go

package info (click to toggle)
docker.io 26.1.5%2Bdfsg1-9
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 68,576 kB
  • sloc: sh: 5,748; makefile: 912; ansic: 664; asm: 228; python: 162
file content (63 lines) | stat: -rw-r--r-- 1,409 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package safepath

import (
	"context"
	"fmt"
	"sync"

	"github.com/containerd/log"
)

type SafePath struct {
	path    string
	cleanup func(ctx context.Context) error
	mutex   sync.Mutex

	// Immutable fields
	sourceBase, sourceSubpath string
}

// Close releases the resources used by the path.
func (s *SafePath) Close(ctx context.Context) error {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	if s.path == "" {
		base, sub := s.SourcePath()
		log.G(ctx).WithFields(log.Fields{
			"path":          s.Path(),
			"sourceBase":    base,
			"sourceSubpath": sub,
		}).Warn("an attempt to close an already closed SafePath")
		return nil
	}

	s.path = ""
	if s.cleanup != nil {
		return s.cleanup(ctx)
	}
	return nil
}

// IsValid return true when path can still be used and wasn't cleaned up by Close.
func (s *SafePath) IsValid() bool {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	return s.path != ""
}

// Path returns a safe, temporary path that can be used to access the original path.
func (s *SafePath) Path() string {
	s.mutex.Lock()
	defer s.mutex.Unlock()
	if s.path == "" {
		panic(fmt.Sprintf("use-after-close attempted for safepath with source [%s, %s]", s.sourceBase, s.sourceSubpath))
	}
	return s.path
}

// SourcePath returns the source path the safepath points to.
func (s *SafePath) SourcePath() (string, string) {
	// No mutex lock because these are immutable.
	return s.sourceBase, s.sourceSubpath
}