Debian Codegraph @

analyzer/fanotify/fanotify.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package fanotify
18
19 import (
20 "fmt"
21 "os/exec"
22 "sync"
23 "syscall"
24 "time"
25
26 "github.com/containerd/stargz-snapshotter/analyzer/fanotify/conn"
27 "github.com/hashicorp/go-multierror"
28 )
29
30 // Fanotifier monitors "/" mountpoint of a new mount namespace and notifies all
31 // accessed files.
32 type Fanotifier struct {
33 cmd *exec.Cmd
34 conn *conn.Client
35 closeOnce sync.Once
36 closeFunc func() error
37 }
38
39 func SpawnFanotifier(fanotifierBin string) (*Fanotifier, error) {
40 // Run fanotifier that monitor "/" in a new mount namespace
41 cmd := exec.Command(fanotifierBin, "fanotify", "/")
42 cmd.SysProcAttr = &syscall.SysProcAttr{
43 Cloneflags: syscall.CLONE_NEWNS,
44 }
45 notifyR, err := cmd.StdoutPipe()
46 if err != nil {
47 return nil, err
48 }
49 notifyW, err := cmd.StdinPipe()
50 if err != nil {
51 return nil, err
52 }
53 if err := cmd.Start(); err != nil {
54 return nil, err
55 }
56
57 return &Fanotifier{
58 cmd: cmd,
59
60 // Connect to the spawned fanotifier over stdio
61 conn: conn.NewClient(notifyR, notifyW, cmd.Process.Pid, 5*time.Second),
62 closeFunc: func() (allErr error) {
63 if err := notifyR.Close(); err != nil {
64 allErr = multierror.Append(allErr, err)
65 }
66 if err := notifyW.Close(); err != nil {
67 allErr = multierror.Append(allErr, err)
68 }
69 return
70 },
71 }, nil
72 }
73
74 // Start starts fanotifier in the new mount namespace
75 func (n *Fanotifier) Start() error {
76 return n.conn.Start()
77 }
78
79 // GetPath gets path notified by the fanotifier.
80 func (n *Fanotifier) GetPath() (string, error) {
81 return n.conn.GetPath()
82 }
83
84 // MountNamespacePath returns the path to the mount namespace where
85 // the fanotifier is monitoring.
86 func (n *Fanotifier) MountNamespacePath() string {
87 return fmt.Sprintf("/proc/%d/ns/mnt", n.cmd.Process.Pid)
88 }
89
90 // Close kills fanotifier process and closes the connection.
91 func (n *Fanotifier) Close() (err error) {
92 n.closeOnce.Do(func() {
93 if err = n.cmd.Process.Kill(); err != nil {
94 return
95 }
96 err = n.closeFunc()
97 })
98 return
99 }