Debian Codegraph @

analyzer/analyzer.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 analyzer
18
19 import (
20 "bufio"
21 "context"
22 "fmt"
23 "io"
24 "os"
25 "os/signal"
26 "strings"
27 "sync"
28 "sync/atomic"
29 "syscall"
30 "time"
31
32 "github.com/containerd/console"
33 "github.com/containerd/containerd"
34 "github.com/containerd/containerd/cio"
35 "github.com/containerd/containerd/cmd/ctr/commands"
36 "github.com/containerd/containerd/cmd/ctr/commands/tasks"
37 "github.com/containerd/containerd/errdefs"
38 "github.com/containerd/containerd/log"
39 "github.com/containerd/containerd/mount"
40 "github.com/containerd/containerd/oci"
41 "github.com/containerd/containerd/platforms"
42 "github.com/containerd/containerd/snapshots"
43 "github.com/containerd/stargz-snapshotter/analyzer/fanotify"
44 "github.com/containerd/stargz-snapshotter/analyzer/recorder"
45 "github.com/opencontainers/go-digest"
46 "github.com/opencontainers/image-spec/identity"
47 runtimespec "github.com/opencontainers/runtime-spec/specs-go"
48 "github.com/rs/xid"
49 )
50
51 var defaultPeriod = 10 * time.Second
52
53 // Analyze analyzes the passed image then store the record of prioritized files into
54 // containerd's content store. This function returns the digest of that record file.
55 // This digest can be used to read record from the content store.
56 func Analyze(ctx context.Context, client *containerd.Client, ref string, opts ...Option) (digest.Digest, error) {
57 var aOpts analyzerOpts
58 for _, o := range opts {
59 o(&aOpts)
60 }
61 if aOpts.terminal && aOpts.waitOnSignal {
62 return "", fmt.Errorf("wait-on-signal option cannot be used with terminal option")
63 }
64
65 target, err := os.MkdirTemp("", "target")
66 if err != nil {
67 return "", err
68 }
69 defer os.RemoveAll(target)
70
71 cs := client.ContentStore()
72 is := client.ImageService()
73 ss := client.SnapshotService(aOpts.snapshotter)
74
75 img, err := is.Get(ctx, ref)
76 if err != nil {
77 return "", err
78 }
79 platformImg := containerd.NewImageWithPlatform(client, img, platforms.Default())
80
81 // Mount the target image
82 // NOTE: We cannot let containerd prepare the rootfs. We create mount namespace *before*
83 // creating the container so containerd's bundle preparation (mounting snapshots to
84 // the bundle directory, etc.) is invisible inside the pre-unshared mount namespace.
85 // This leads to runc using empty directory as the rootfs.
86 if unpacked, err := platformImg.IsUnpacked(ctx, aOpts.snapshotter); err != nil {
87 return "", err
88 } else if !unpacked {
89 if err := platformImg.Unpack(ctx, aOpts.snapshotter); err != nil {
90 return "", err
91 }
92 }
93 cleanup, err := mountImage(ctx, ss, platformImg, target)
94 if err != nil {
95 return "", err
96 }
97 defer cleanup()
98
99 // Spawn a fanotifier process in a new mount namespace and setup recorder.
100 fanotifier, err := fanotify.SpawnFanotifier("/proc/self/exe")
101 if err != nil {
102 return "", fmt.Errorf("failed to spawn fanotifier: %w", err)
103 }
104 defer func() {
105 if err := fanotifier.Close(); err != nil {
106 log.G(ctx).WithError(err).Warnf("failed to close fanotifier")
107 }
108 }()
109
110 // Prepare the spec based on the specified image and runtime options.
111 var sOpts []oci.SpecOpts
112 if aOpts.specOpts != nil {
113 gotOpts, done, err := aOpts.specOpts(platformImg, target)
114 if err != nil {
115 return "", err
116 }
117 defer func() {
118 if err := done(); err != nil {
119 log.G(ctx).WithError(err).Warnf("failed to cleanup container")
120 return
121 }
122 }()
123 sOpts = append(sOpts, gotOpts...)
124 } else {
125 sOpts = append(sOpts,
126 oci.WithDefaultSpec(),
127 oci.WithDefaultUnixDevices,
128 oci.WithRootFSPath(target),
129 oci.WithImageConfig(platformImg),
130 )
131 }
132 sOpts = append(sOpts, oci.WithLinuxNamespace(runtimespec.LinuxNamespace{
133 Type: runtimespec.MountNamespace,
134 Path: fanotifier.MountNamespacePath(), // use mount namespace that the fanotifier created
135 }))
136
137 // Create the container and the task
138 var container containerd.Container
139 for i := 0; i < 3; i++ {
140 id := xid.New().String()
141 var s runtimespec.Spec
142 container, err = client.NewContainer(ctx, id,
143 containerd.WithImage(platformImg),
144 containerd.WithSnapshotter(aOpts.snapshotter),
145 containerd.WithImageStopSignal(platformImg, "SIGKILL"),
146
147 // WithImageConfig depends on WithImage and WithSnapshotter for resolving
148 // username (accesses to /etc/{passwd,group} files on the rootfs)
149 containerd.WithSpec(&s, sOpts...),
150 )
151 if err != nil {
152 if errdefs.IsAlreadyExists(err) {
153 log.G(ctx).WithError(err).Warnf("failed to create container")
154 continue
155 }
156 return "", err
157 }
158 break
159 }
160 if container == nil {
161 return "", fmt.Errorf("failed to create container")
162 }
163 defer container.Delete(ctx, containerd.WithSnapshotCleanup)
164 var ioCreator cio.Creator
165 var con console.Console
166 waitLine := newLineWaiter(aOpts.waitLineOut)
167 stdinC := newLazyReadCloser(os.Stdin)
168 if aOpts.terminal {
169 if !aOpts.stdin {
170 return "", fmt.Errorf("terminal cannot be used if stdin isn't enabled")
171 }
172 con = console.Current()
173 defer con.Reset()
174 if err := con.SetRaw(); err != nil {
175 return "", err
176 }
177 // On terminal mode, the "stderr" field is unused.
178 ioCreator = cio.NewCreator(cio.WithStreams(con, waitLine.registerWriter(con), nil), cio.WithTerminal)
179 } else if aOpts.stdin {
180 ioCreator = cio.NewCreator(cio.WithStreams(stdinC, waitLine.registerWriter(os.Stdout), os.Stderr))
181 } else {
182 ioCreator = cio.NewCreator(cio.WithStreams(nil, waitLine.registerWriter(os.Stdout), os.Stderr))
183 }
184 task, err := container.NewTask(ctx, ioCreator)
185 if err != nil {
186 return "", err
187 }
188 stdinC.registerCloser(func() { // Ensure to close IO when stdin get EOF
189 task.CloseIO(ctx, containerd.WithStdinCloser)
190 })
191
192 // Start to monitor "/" and run the task.
193 rc, err := recorder.NewImageRecorder(ctx, cs, img, platforms.Default())
194 if err != nil {
195 return "", err
196 }
197 defer rc.Close()
198 if err := fanotifier.Start(); err != nil {
199 return "", fmt.Errorf("failed to start fanotifier: %w", err)
200 }
201 var fanotifierClosed bool
202 var fanotifierClosedMu sync.Mutex
203 go func() {
204 var successCount int
205 defer func() {
206 log.G(ctx).Debugf("success record %d path", successCount)
207 }()
208 for {
209 path, err := fanotifier.GetPath()
210 if err != nil {
211 if err == io.EOF {
212 fanotifierClosedMu.Lock()
213 isFanotifierClosed := fanotifierClosed
214 fanotifierClosedMu.Unlock()
215 if isFanotifierClosed {
216 break
217 }
218 }
219 log.G(ctx).WithError(err).Error("failed to get notified path")
220 break
221 }
222 if err := rc.Record(path); err != nil {
223 log.G(ctx).WithError(err).Debugf("failed to record %q", path)
224 }
225 successCount++
226 }
227 }()
228 if aOpts.terminal {
229 if err := tasks.HandleConsoleResize(ctx, task, con); err != nil {
230 log.G(ctx).WithError(err).Error("failed to resize console")
231 }
232 } else {
233 sigc := commands.ForwardAllSignals(ctx, task)
234 defer commands.StopCatch(sigc)
235 }
236 if err := task.Start(ctx); err != nil {
237 return "", err
238 }
239
240 // Wait until the task exit
241 var status containerd.ExitStatus
242 var killOk bool
243 if aOpts.waitOnSignal { // NOTE: not functional with `terminal` option
244 log.G(ctx).Infof("press Ctrl+C to terminate the container")
245 status, killOk, err = waitOnSignal(ctx, container, task)
246 if err != nil {
247 return "", err
248 }
249 } else {
250 if aOpts.period <= 0 {
251 aOpts.period = defaultPeriod
252 }
253 log.G(ctx).Infof("waiting for %v ...", aOpts.period)
254 status, killOk, err = waitOnTimeout(ctx, container, task, aOpts.period, waitLine)
255 if err != nil {
256 return "", err
257 }
258 }
259 if !killOk {
260 log.G(ctx).Warnf("failed to exit task %v; manually kill it", task.ID())
261 } else {
262 code, _, err := status.Result()
263 if err != nil {
264 return "", err
265 }
266 log.G(ctx).Infof("container exit with code %v", code)
267 if _, err := task.Delete(ctx); err != nil {
268 return "", err
269 }
270 }
271
272 // ensure no record comes in
273 fanotifierClosedMu.Lock()
274 fanotifierClosed = true
275 fanotifierClosedMu.Unlock()
276 if err := fanotifier.Close(); err != nil {
277 log.G(ctx).WithError(err).Warnf("failed to cleanup fanotifier")
278 }
279
280 // Finish recording
281 return rc.Commit(ctx)
282 }
283
284 func mountImage(ctx context.Context, ss snapshots.Snapshotter, image containerd.Image, mountpoint string) (func(), error) {
285 diffIDs, err := image.RootFS(ctx)
286 if err != nil {
287 return nil, err
288 }
289 mounts, err := ss.Prepare(ctx, mountpoint, identity.ChainID(diffIDs).String())
290 if err != nil {
291 return nil, err
292 }
293 if err := mount.All(mounts, mountpoint); err != nil {
294 if err := ss.Remove(ctx, mountpoint); err != nil && !errdefs.IsNotFound(err) {
295 log.G(ctx).WithError(err).Warnf("failed to cleanup snapshot after mount error")
296 }
297 return nil, fmt.Errorf("failed to mount rootfs at %q: %w", mountpoint, err)
298 }
299 return func() {
300 if err := mount.UnmountAll(mountpoint, 0); err != nil {
301 log.G(ctx).WithError(err).Warnf("failed to unmount snapshot")
302 }
303 if err := ss.Remove(ctx, mountpoint); err != nil && !errdefs.IsNotFound(err) {
304 log.G(ctx).WithError(err).Warnf("failed to cleanup snapshot")
305 }
306 }, nil
307 }
308
309 func waitOnSignal(ctx context.Context, container containerd.Container, task containerd.Task) (containerd.ExitStatus, bool, error) {
310 statusC, err := task.Wait(ctx)
311 if err != nil {
312 return containerd.ExitStatus{}, false, err
313 }
314 sc := make(chan os.Signal, 1)
315 signal.Notify(sc, syscall.SIGINT)
316 defer signal.Stop(sc)
317 select {
318 case status := <-statusC:
319 return status, true, nil
320 case <-sc:
321 log.G(ctx).Info("signal detected")
322 status, err := killTask(ctx, container, task, statusC)
323 if err != nil {
324 log.G(ctx).WithError(err).Warnf("failed to kill container")
325 return containerd.ExitStatus{}, false, nil
326 }
327 return status, true, nil
328 }
329 }
330
331 func waitOnTimeout(ctx context.Context, container containerd.Container, task containerd.Task, period time.Duration, line *lineWaiter) (containerd.ExitStatus, bool, error) {
332 statusC, err := task.Wait(ctx)
333 if err != nil {
334 return containerd.ExitStatus{}, false, err
335 }
336 select {
337 case status := <-statusC:
338 return status, true, nil
339 case l := <-line.waitCh:
340 log.G(ctx).Infof("Waiting line detected %q; killing task", l)
341 case <-time.After(period):
342 log.G(ctx).Warnf("killing task. the time period to monitor access log (%s) has timed out", period.String())
343 }
344 status, err := killTask(ctx, container, task, statusC)
345 if err != nil {
346 log.G(ctx).WithError(err).Warnf("failed to kill container")
347 return containerd.ExitStatus{}, false, nil
348 }
349 return status, true, nil
350 }
351
352 func killTask(ctx context.Context, container containerd.Container, task containerd.Task, statusC <-chan containerd.ExitStatus) (containerd.ExitStatus, error) {
353 sig, err := containerd.GetStopSignal(ctx, container, syscall.SIGKILL)
354 if err != nil {
355 return containerd.ExitStatus{}, err
356 }
357 if err := task.Kill(ctx, sig, containerd.WithKillAll); err != nil && !errdefs.IsNotFound(err) {
358 return containerd.ExitStatus{}, fmt.Errorf("forward SIGKILL: %w", err)
359 }
360 select {
361 case status := <-statusC:
362 return status, nil
363 case <-time.After(5 * time.Second):
364 return containerd.ExitStatus{}, fmt.Errorf("timeout")
365 }
366 }
367
368 type lazyReadCloser struct {
369 reader io.Reader
370 closer func()
371 closerMu sync.Mutex
372 initCond *sync.Cond
373 initialized int64
374 }
375
376 func newLazyReadCloser(r io.Reader) *lazyReadCloser {
377 rc := &lazyReadCloser{reader: r, initCond: sync.NewCond(&sync.Mutex{})}
378 return rc
379 }
380
381 func (s *lazyReadCloser) registerCloser(closer func()) {
382 s.closerMu.Lock()
383 s.closer = closer
384 s.closerMu.Unlock()
385 atomic.AddInt64(&s.initialized, 1)
386 s.initCond.Broadcast()
387 }
388
389 func (s *lazyReadCloser) Read(p []byte) (int, error) {
390 if atomic.LoadInt64(&s.initialized) <= 0 {
391 // wait until initialized
392 s.initCond.L.Lock()
393 if atomic.LoadInt64(&s.initialized) <= 0 {
394 s.initCond.Wait()
395 }
396 s.initCond.L.Unlock()
397 }
398
399 n, err := s.reader.Read(p)
400 if err == io.EOF {
401 s.closerMu.Lock()
402 s.closer()
403 s.closerMu.Unlock()
404 }
405 return n, err
406 }
407
408 func newLineWaiter(s string) *lineWaiter {
409 return &lineWaiter{
410 waitCh: make(chan string),
411 waitLine: s,
412 }
413 }
414
415 type lineWaiter struct {
416 waitCh chan string
417 waitLine string
418 }
419
420 func (lw *lineWaiter) registerWriter(w io.Writer) io.Writer {
421 if lw.waitLine == "" {
422 return w
423 }
424
425 pr, pw := io.Pipe()
426 go func() {
427 scanner := bufio.NewScanner(pr)
428 for scanner.Scan() {
429 if strings.Contains(scanner.Text(), lw.waitLine) {
430 lw.waitCh <- lw.waitLine
431 }
432 }
433 if _, err := io.Copy(io.Discard, pr); err != nil {
434 pr.CloseWithError(err)
435 return
436 }
437 }()
438
439 return io.MultiWriter(w, pw)
440 }