-
Notifications
You must be signed in to change notification settings - Fork 13
/
containerd_engine.go
522 lines (435 loc) · 14.7 KB
/
containerd_engine.go
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/*
* Copyright 2022 Holoinsight Project Authors. Licensed under Apache-2.0.
*/
package engine
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"github.com/containerd/containerd"
"github.com/containerd/containerd/api/services/tasks/v1"
"github.com/containerd/containerd/cio"
"github.com/containerd/containerd/defaults"
runc_options "github.com/containerd/containerd/runtime/v2/runc/options"
"github.com/traas-stack/holoinsight-agent/pkg/core"
"github.com/traas-stack/holoinsight-agent/pkg/cri/containerdutils"
"github.com/traas-stack/holoinsight-agent/pkg/logger"
"github.com/traas-stack/holoinsight-agent/pkg/util"
"go.uber.org/zap"
"io"
"os"
"path/filepath"
"strings"
containerstore "github.com/containerd/containerd/pkg/cri/store/container"
sandboxstore "github.com/containerd/containerd/pkg/cri/store/sandbox"
_ "github.com/containerd/containerd/runtime"
"github.com/containerd/typeurl"
"github.com/google/cadvisor/container/containerd/namespaces"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/traas-stack/holoinsight-agent/pkg/cri"
)
const (
IDLength = 64
k8sNs = "k8s.io"
)
type (
// ContainerdContainerEngine Containerd container engine
ContainerdContainerEngine struct {
Client *containerd.Client
fifoDir string
}
)
var (
// Make sure *ContainerdContainerEngine impl cri.ContainerEngine
_ cri.ContainerEngine = &ContainerdContainerEngine{}
)
func init() {
typeurl.Register(&containerstore.Metadata{},
"github.com/containerd/cri/pkg/store/container", "Metadata")
typeurl.Register(&sandboxstore.Metadata{},
"github.com/containerd/cri/pkg/store/sandbox", "Metadata")
}
func (e *ContainerdContainerEngine) Init() error {
// When execute 'ctr exec' using containerd sdk, it requires:
// 1. fifo dir is visible to current process (HoloInsight-Agent)
// Because HoloInsight-Agent daemonset runs in its own MNT namespace, the filesystems of it and host are different.
// But we mount hostPath `/usr/local/holoinsight/agent/data` to containerPath `/usr/local/holoinsight/agent/data`.
// So only these few directory are the same in two filesystems.
// So we can set the FIFODir for 'containerd exec' to '/usr/local/holoinsight/agent/data/containrd-fifo'.
workdir, err := os.Getwd()
if err != nil {
return err
}
e.fifoDir = filepath.Join(workdir, "data", "containerd-fifo")
if err := os.MkdirAll(e.fifoDir, 0755); err != nil {
return err
}
//if err := mount.SetTempMountLocation(filepath.Join(workdir, "data", "containerd-mount")); err != nil {
// return err
//}
// TODO events
//go func() {
//
// eventCh, errCh := e.Client.EventService().Subscribe(context.Background())
// select {
// case event := <-eventCh:
// logger.Dockerz("[event]", zap.String("engine", e.Type()), zap.Any("event", event))
// case err := <-errCh:
// logger.Dockerz("[event] error", zap.String("engine", e.Type()), zap.Error(err))
// }
//}()
return nil
}
func (e *ContainerdContainerEngine) Type() string {
return "containerd"
}
func wrapK8sCtx(ctx context.Context) context.Context {
return namespaces.WithNamespace(ctx, k8sNs)
}
func (e *ContainerdContainerEngine) ListAllContainers(ctx context.Context) ([]*cri.EngineSimpleContainer, error) {
ctx = wrapK8sCtx(ctx)
containers, err := e.Client.ContainerService().List(ctx)
if err != nil {
return nil, err
}
items := make([]*cri.EngineSimpleContainer, len(containers))
for i := range containers {
copy := containers[i]
items[i] = &cri.EngineSimpleContainer{
ID: copy.ID,
Labels: copy.Labels,
Source: copy,
}
}
return items, nil
}
func (e *ContainerdContainerEngine) GetContainerDetail(ctx context.Context, cid string) (*cri.EngineDetailContainer, error) {
ctx = wrapK8sCtx(ctx)
container, err := e.Client.ContainerService().Get(ctx, cid)
if err != nil {
return nil, err
}
spec := specs.Spec{}
if err := typeurl.UnmarshalToByTypeURL(container.Spec.GetTypeUrl(), container.Spec.GetValue(), &spec); err != nil {
return nil, err
}
containerMeta := containerstore.Metadata{}
sandboxMeta := sandboxstore.Metadata{}
for key, ext := range container.Extensions {
switch key {
case "io.cri-containerd.container.metadata":
if err = typeurl.UnmarshalToByTypeURL(ext.GetTypeUrl(), ext.GetValue(), &containerMeta); err != nil {
return nil, err
}
case "io.cri-containerd.sandbox.metadata":
if err = typeurl.UnmarshalToByTypeURL(ext.GetTypeUrl(), ext.GetValue(), &sandboxMeta); err != nil {
return nil, err
}
}
}
detail := &cri.EngineDetailContainer{
ID: container.ID,
Labels: container.Labels,
Env: spec.Process.Env,
Source: container,
Hostname: spec.Hostname,
IsSandbox: container.Labels["io.cri-containerd.kind"] == "sandbox",
Mounts: nil,
Runtime: "",
SandboxId: "",
// Name formats are different in docker and containerd
Name: "",
MergedDir: "",
NetworkMode: "",
LogPath: containerMeta.LogPath,
State: cri.ContainerState{
Pid: 0,
},
}
if taskResp, err := e.Client.TaskService().Get(ctx, &tasks.GetRequest{
ContainerID: container.ID,
}); err == nil {
detail.State.Pid = int(taskResp.Process.Pid)
detail.State.Status = strings.ToLower(taskResp.Process.Status.String())
} else {
// no task for container : like container dead in docker
}
if detail.IsSandbox {
detail.Name = sandboxMeta.Name
} else {
detail.Name = containerMeta.Name
detail.SandboxId = containerMeta.SandboxID
// or
// detail.SandboxId = spec.Annotations["io.kubernetes.cri.sandbox-id"]
}
var runtime interface{}
switch container.Runtime.Name {
case "io.containerd.runc.v2":
detail.Runtime = "runc"
runcOptions := runc_options.Options{}
err = typeurl.UnmarshalToByTypeURL(container.Runtime.Options.GetTypeUrl(), container.Runtime.Options.GetValue(), &runcOptions)
runtime = &runcOptions
default:
// TODO other runtime
detail.Runtime = "unknown"
}
if !detail.IsSandbox {
// According to actual measurements, spec.mounts is different from containerMeta.Config.Mounts.
// It's better to use spec.mounts.
// spec.mounts stores the mounts that are actually effective at the containerd level,
// which includes the directories declared with the VOLUME keyword in the Dockerfile.
for _, mount := range spec.Mounts {
if !util.StringSliceContains(mount.Options, "rw") {
continue
}
detail.Mounts = append(detail.Mounts, &cri.MountPoint{
Source: mount.Source,
Destination: mount.Destination,
RW: true,
})
}
// containerMeta.Config.Mounts stores mounts explicitly set by k8s.
//for _, mount := range containerMeta.Config.Mounts {
// detail.Mounts = append(detail.Mounts, &cri.MountPoint{
// Source: mount.HostPath,
// Destination: mount.ContainerPath,
// RW: !mount.Readonly,
// })
//}
}
if detail.IsSandbox {
detail.NetworkMode = "netns:" + sandboxMeta.NetNSPath
// TODO detail.PidMode
}
// I don't know how to get containerd's state dir.
// But I know its default value.
// Tested OK on containerd v1.6.8.
maybeContainerdStateDirs := []string{defaults.DefaultStateDir, containerdutils.K3sDefaultStateDir}
for _, stateDir := range maybeContainerdStateDirs {
// TODO It seems that for the old version of containerd, the rootfs of the container is not this.
containerRootfs := filepath.Join(stateDir, "io.containerd.runtime.v2.task", "k8s.io", cid, "rootfs")
if st, err := os.Stat(filepath.Join(core.GetHostfs(), containerRootfs)); err == nil && st.IsDir() {
detail.MergedDir = containerRootfs
break
}
}
logger.Debugz("[containerd] details",
zap.String("cid", cid),
zap.Any("container", &container),
zap.Any("runtime", &runtime),
zap.Any("spec", &spec),
zap.Any("containerMeta", &containerMeta),
zap.Any("sandboxMeta", &sandboxMeta),
)
return detail, nil
}
func (e *ContainerdContainerEngine) Exec(ctx context.Context, c *cri.Container, req cri.ExecRequest) (cri.ExecResult, error) {
// The code for this function refers to: https://github.com/containerd/containerd/blob/main/cmd/ctr/commands/tasks/exec.go
ctx = wrapK8sCtx(ctx)
invalidResult := cri.ExecResult{Cmd: strings.Join(req.Cmd, " "), ExitCode: -1}
container, err := e.Client.LoadContainer(ctx, c.Id)
if err != nil {
return invalidResult, err
}
spec, err := container.Spec(ctx)
if err != nil {
return invalidResult, err
}
// TODO
// WithUser depends on mounts. This will fail when run inside a container.
// Unless I manually copy a copy of the code of oci.WithUsername(), add the prefix of /hostfs to the mount directory.
// container2, err := container.Info(ctx)
// if err != nil {
// return invalidResult, err
// }
// if err := oci.WithUserID(0)(ctx, e.Client, &container2, spec); err != nil {
// return invalidResult, err
// }
// It just so happens that in most cases we execute as root, so simply set this to 0
// TODO I found there is no root user in prometheus/node-exporter image.
// This image is very thin!
spec.Process.User.UID = 0
spec.Process.User.GID = 0
spec.Process.User.AdditionalGids = []uint32{}
spec.Process.User.Umask = nil
pspec := spec.Process
pspec.Terminal = false
pspec.Args = req.Cmd
if req.WorkingDir != "" {
pspec.Cwd = req.WorkingDir
}
// Append user specified env
pspec.Env = append(pspec.Env, req.Env...)
task, err := container.Task(ctx, nil)
if err != nil {
return invalidResult, err
}
stdout := bytes.NewBuffer(nil)
stderr := bytes.NewBuffer(nil)
var ioCreator cio.Creator
var stdinWrapper *util.ReaderCloserFunc
if req.Input != nil {
stdinWrapper = &util.ReaderCloserFunc{
Reader: req.Input,
}
ioCreator = cio.NewCreator(cio.WithStreams(stdinWrapper, stdout, stderr), cio.WithFIFODir(e.fifoDir))
} else {
ioCreator = cio.NewCreator(cio.WithStreams(nil, stdout, stderr), cio.WithFIFODir(e.fifoDir))
}
// Containerd has a exec id limit with max length = 76
execID := "exec-" + generateID()
process, err := task.Exec(ctx, execID, pspec, ioCreator)
if err != nil {
return invalidResult, err
}
if stdinWrapper != nil {
stdinWrapper.Closer = func() { process.CloseIO(ctx, containerd.WithStdinCloser) }
}
defer process.Delete(ctx)
statusC, err := process.Wait(ctx)
if err != nil {
return invalidResult, err
}
if err := process.Start(ctx); err != nil {
return invalidResult, err
}
var status containerd.ExitStatus
select {
case <-ctx.Done():
// timeout
return invalidResult, ctx.Err()
case status = <-statusC:
}
code, _, err := status.Result()
// When exec successfully but with exitCode!=0, I wrap it as an error. This forces developers to handle errors.
if err == nil && code != 0 {
err = fmt.Errorf("exitcode=[%d] stdout=[%s] stderr=[%s]", code, stdout.String(), stderr.String())
}
return cri.ExecResult{Cmd: invalidResult.Cmd, ExitCode: int(code), Stdout: stdout, Stderr: stderr}, err
}
func (e *ContainerdContainerEngine) CopyToContainer(ctx context.Context, c *cri.Container, src, dst string) error {
return errors.New("CopyToContainer unsupported")
}
func (e *ContainerdContainerEngine) CopyFromContainer(ctx context.Context, c *cri.Container, src, dst string) error {
return errors.New("CopyFromContainer unsupported")
}
func (e *ContainerdContainerEngine) Supports(feature cri.ContainerEngineFeature) bool {
switch feature {
case cri.ContainerEngineFeatureCopy:
return false
default:
return false
}
}
// generateID is copy from nerdctl idgen.go
// Generate id with length = 64
func generateID() string {
bytesLength := IDLength / 2
b := make([]byte, bytesLength)
n, err := rand.Read(b)
if err != nil {
panic(err)
}
if n != bytesLength {
panic(fmt.Errorf("expected %d bytes, got %d bytes", bytesLength, n))
}
return hex.EncodeToString(b)
}
func (e *ContainerdContainerEngine) ExecAsync(ctx context.Context, c *cri.Container, req cri.ExecRequest) (cri.ExecAsyncResult, error) {
// The code for this function refers to: https://github.com/containerd/containerd/blob/main/cmd/ctr/commands/tasks/exec.go
ctx = wrapK8sCtx(ctx)
result := make(chan cri.ExecAsyncResultCode)
invalidResult := cri.ExecAsyncResult{Cmd: strings.Join(req.Cmd, " "), Result: result}
container, err := e.Client.LoadContainer(ctx, c.Id)
if err != nil {
return invalidResult, err
}
spec, err := container.Spec(ctx)
if err != nil {
return invalidResult, err
}
// TODO
// WithUser depends on mounts. This will fail when run inside a container.
// Unless I manually copy a copy of the code of oci.WithUsername(), add the prefix of /hostfs to the mount directory.
// container2, err := container.Info(ctx)
// if err != nil {
// return invalidResult, err
// }
// if err := oci.WithUserID(0)(ctx, e.Client, &container2, spec); err != nil {
// return invalidResult, err
// }
// It just so happens that in most cases we execute as root, so simply set this to 0
// TODO I found there is no root user in prometheus/node-exporter image.
// This image is very thin!
spec.Process.User.UID = 0
spec.Process.User.GID = 0
spec.Process.User.AdditionalGids = []uint32{}
spec.Process.User.Umask = nil
pspec := spec.Process
pspec.Terminal = false
pspec.Args = req.Cmd
if req.WorkingDir != "" {
pspec.Cwd = req.WorkingDir
}
// Append user specified env
pspec.Env = req.Env
task, err := container.Task(ctx, nil)
if err != nil {
return invalidResult, err
}
stdoutR, stdoutW := io.Pipe()
stderrR, stderrW := io.Pipe()
var ioCreator cio.Creator
var stdinWrapper *util.ReaderCloserFunc
if req.Input != nil {
stdinWrapper = &util.ReaderCloserFunc{
Reader: req.Input,
}
ioCreator = cio.NewCreator(cio.WithStreams(stdinWrapper, stdoutW, stderrW), cio.WithFIFODir(e.fifoDir))
} else {
ioCreator = cio.NewCreator(cio.WithStreams(nil, stdoutW, stderrW), cio.WithFIFODir(e.fifoDir))
}
// Containerd has a exec id limit with max length = 76
execID := "exec-" + generateID()
process, err := task.Exec(ctx, execID, pspec, ioCreator)
if err != nil {
return invalidResult, err
}
if stdinWrapper != nil {
stdinWrapper.Closer = func() { process.CloseIO(ctx, containerd.WithStdinCloser) }
}
// defer process.Delete(ctx)
statusC, err := process.Wait(ctx)
if err != nil {
return invalidResult, err
}
if err := process.Start(ctx); err != nil {
return invalidResult, err
}
go func() {
defer process.Delete(ctx)
var status containerd.ExitStatus
select {
case <-ctx.Done():
// timeout
result <- cri.ExecAsyncResultCode{
Code: -1,
Err: ctx.Err(),
}
case status = <-statusC:
code, _, err := status.Result()
// When exec successfully but with exitCode!=0, I wrap it as an error. This forces developers to handle errors.
if err == nil && code != 0 {
err = fmt.Errorf("exitcode=[%d]", code)
}
result <- cri.ExecAsyncResultCode{
Code: int(code),
Err: err,
}
}
}()
return cri.ExecAsyncResult{Cmd: invalidResult.Cmd, Result: result, Stdout: stdoutR, Stderr: stderrR}, err
}