Debian Codegraph @

cmd/containerd-shim-runc-v2/manager/manager_linux.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 manager
18
19 import (
20 "bytes"
21 "context"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "net"
27 "os"
28 "os/exec"
29 "path/filepath"
30 goruntime "runtime"
31 "syscall"
32 "time"
33
34 "github.com/containerd/cgroups/v3"
35 "github.com/containerd/cgroups/v3/cgroup1"
36 cgroupsv2 "github.com/containerd/cgroups/v3/cgroup2"
37 "github.com/containerd/containerd/api/types"
38 "github.com/containerd/containerd/api/types/runc/options"
39 "github.com/containerd/containerd/v2/cmd/containerd-shim-runc-v2/process"
40 "github.com/containerd/containerd/v2/cmd/containerd-shim-runc-v2/runc"
41 "github.com/containerd/containerd/v2/core/mount"
42 "github.com/containerd/containerd/v2/pkg/namespaces"
43 "github.com/containerd/containerd/v2/pkg/schedcore"
44 "github.com/containerd/containerd/v2/pkg/shim"
45 "github.com/containerd/containerd/v2/version"
46 "github.com/containerd/errdefs"
47 runcC "github.com/containerd/go-runc"
48 "github.com/containerd/log"
49 "github.com/containerd/typeurl/v2"
50 "github.com/opencontainers/runtime-spec/specs-go/features"
51 "golang.org/x/sys/unix"
52 )
53
54 // NewShimManager returns an implementation of the shim manager
55 // using runc
56 func NewShimManager(name string) shim.Manager {
57 return &manager{
58 name: name,
59 }
60 }
61
62 // group labels specifies how the shim groups services.
63 // currently supports a runc.v2 specific .group label and the
64 // standard k8s pod label. Order matters in this list
65 var groupLabels = []string{
66 "io.containerd.runc.v2.group",
67 "io.kubernetes.cri.sandbox-id",
68 }
69
70 // spec is a shallow version of [oci.Spec] containing only the
71 // fields we need for the hook. We use a shallow struct to reduce
72 // the overhead of unmarshaling.
73 type spec struct {
74 // Annotations contains arbitrary metadata for the container.
75 Annotations map[string]string `json:"annotations,omitempty"`
76 }
77
78 type manager struct {
79 name string
80 }
81
82 func newCommand(ctx context.Context, id, containerdAddress, containerdTTRPCAddress string, debug bool) (*exec.Cmd, error) {
83 ns, err := namespaces.NamespaceRequired(ctx)
84 if err != nil {
85 return nil, err
86 }
87 self, err := os.Executable()
88 if err != nil {
89 return nil, err
90 }
91 cwd, err := os.Getwd()
92 if err != nil {
93 return nil, err
94 }
95 args := []string{
96 "-namespace", ns,
97 "-id", id,
98 "-address", containerdAddress,
99 }
100 if debug {
101 args = append(args, "-debug")
102 }
103 cmd := exec.Command(self, args...)
104 cmd.Dir = cwd
105 cmd.Env = append(os.Environ(), "GOMAXPROCS=4")
106 cmd.Env = append(cmd.Env, "OTEL_SERVICE_NAME=containerd-shim-"+id)
107 cmd.SysProcAttr = &syscall.SysProcAttr{
108 Setpgid: true,
109 }
110 return cmd, nil
111 }
112
113 func readSpec() (*spec, error) {
114 const configFileName = "config.json"
115 f, err := os.Open(configFileName)
116 if err != nil {
117 return nil, err
118 }
119 defer f.Close()
120 var s spec
121 if err := json.NewDecoder(f).Decode(&s); err != nil {
122 return nil, err
123 }
124 return &s, nil
125 }
126
127 func (m manager) Name() string {
128 return m.name
129 }
130
131 type shimSocket struct {
132 addr string
133 s *net.UnixListener
134 f *os.File
135 }
136
137 func (s *shimSocket) Close() {
138 if s.s != nil {
139 s.s.Close()
140 }
141 if s.f != nil {
142 s.f.Close()
143 }
144 _ = shim.RemoveSocket(s.addr)
145 }
146
147 func newShimSocket(ctx context.Context, path, id string, debug bool) (*shimSocket, error) {
148 address, err := shim.SocketAddress(ctx, path, id, debug)
149 if err != nil {
150 return nil, err
151 }
152 socket, err := shim.NewSocket(address)
153 if err != nil {
154 // the only time where this would happen is if there is a bug and the socket
155 // was not cleaned up in the cleanup method of the shim or we are using the
156 // grouping functionality where the new process should be run with the same
157 // shim as an existing container
158 if !shim.SocketEaddrinuse(err) {
159 return nil, fmt.Errorf("create new shim socket: %w", err)
160 }
161 if !debug && shim.CanConnect(address) {
162 return &shimSocket{addr: address}, errdefs.ErrAlreadyExists
163 }
164 if err := shim.RemoveSocket(address); err != nil {
165 return nil, fmt.Errorf("remove pre-existing socket: %w", err)
166 }
167 if socket, err = shim.NewSocket(address); err != nil {
168 return nil, fmt.Errorf("try create new shim socket 2x: %w", err)
169 }
170 }
171 s := &shimSocket{
172 addr: address,
173 s: socket,
174 }
175 f, err := socket.File()
176 if err != nil {
177 s.Close()
178 return nil, err
179 }
180 s.f = f
181 return s, nil
182 }
183
184 func (manager) Start(ctx context.Context, id string, opts shim.StartOpts) (_ shim.BootstrapParams, retErr error) {
185 var params shim.BootstrapParams
186 params.Version = 3
187 params.Protocol = "ttrpc"
188
189 cmd, err := newCommand(ctx, id, opts.Address, opts.TTRPCAddress, opts.Debug)
190 if err != nil {
191 return params, err
192 }
193 grouping := id
194 spec, err := readSpec()
195 if err != nil {
196 return params, err
197 }
198 for _, group := range groupLabels {
199 if groupID, ok := spec.Annotations[group]; ok {
200 grouping = groupID
201 break
202 }
203 }
204
205 var sockets []*shimSocket
206 defer func() {
207 if retErr != nil {
208 for _, s := range sockets {
209 s.Close()
210 }
211 }
212 }()
213
214 s, err := newShimSocket(ctx, opts.Address, grouping, false)
215 if err != nil {
216 if errdefs.IsAlreadyExists(err) {
217 params.Address = s.addr
218 return params, nil
219 }
220 return params, err
221 }
222 sockets = append(sockets, s)
223 cmd.ExtraFiles = append(cmd.ExtraFiles, s.f)
224
225 if opts.Debug {
226 s, err = newShimSocket(ctx, opts.Address, grouping, true)
227 if err != nil {
228 return params, err
229 }
230 sockets = append(sockets, s)
231 cmd.ExtraFiles = append(cmd.ExtraFiles, s.f)
232 }
233
234 goruntime.LockOSThread()
235 if os.Getenv("SCHED_CORE") != "" {
236 if err := schedcore.Create(schedcore.ProcessGroup); err != nil {
237 return params, fmt.Errorf("enable sched core support: %w", err)
238 }
239 }
240
241 if err := cmd.Start(); err != nil {
242 return params, err
243 }
244
245 goruntime.UnlockOSThread()
246
247 defer func() {
248 if retErr != nil {
249 cmd.Process.Kill()
250 }
251 }()
252 // make sure to wait after start
253 go cmd.Wait()
254
255 if opts, err := shim.ReadRuntimeOptions[*options.Options](os.Stdin); err == nil {
256 if opts.ShimCgroup != "" {
257 if cgroups.Mode() == cgroups.Unified {
258 cg, err := cgroupsv2.Load(opts.ShimCgroup)
259 if err != nil {
260 return params, fmt.Errorf("failed to load cgroup %s: %w", opts.ShimCgroup, err)
261 }
262 if err := cg.AddProc(uint64(cmd.Process.Pid)); err != nil {
263 return params, fmt.Errorf("failed to join cgroup %s: %w", opts.ShimCgroup, err)
264 }
265 } else {
266 cg, err := cgroup1.Load(cgroup1.StaticPath(opts.ShimCgroup))
267 if err != nil {
268 return params, fmt.Errorf("failed to load cgroup %s: %w", opts.ShimCgroup, err)
269 }
270 if err := cg.AddProc(uint64(cmd.Process.Pid)); err != nil {
271 return params, fmt.Errorf("failed to join cgroup %s: %w", opts.ShimCgroup, err)
272 }
273 }
274 }
275 }
276
277 if err := shim.AdjustOOMScore(cmd.Process.Pid); err != nil {
278 return params, fmt.Errorf("failed to adjust OOM score for shim: %w", err)
279 }
280
281 params.Address = sockets[0].addr
282 return params, nil
283 }
284
285 func (manager) Stop(ctx context.Context, id string) (shim.StopStatus, error) {
286 cwd, err := os.Getwd()
287 if err != nil {
288 return shim.StopStatus{}, err
289 }
290
291 path := filepath.Join(filepath.Dir(cwd), id)
292 ns, err := namespaces.NamespaceRequired(ctx)
293 if err != nil {
294 return shim.StopStatus{}, err
295 }
296 runtime, err := runc.ReadRuntime(path)
297 if err != nil && !os.IsNotExist(err) {
298 return shim.StopStatus{}, err
299 }
300 opts, err := runc.ReadOptions(path)
301 if err != nil {
302 return shim.StopStatus{}, err
303 }
304 root := process.RuncRoot
305 if opts != nil && opts.Root != "" {
306 root = opts.Root
307 }
308
309 r := process.NewRunc(root, path, ns, runtime, false)
310 if err := r.Delete(ctx, id, &runcC.DeleteOpts{
311 Force: true,
312 }); err != nil {
313 log.G(ctx).WithError(err).Warn("failed to remove runc container")
314 }
315 if err := mount.UnmountRecursive(filepath.Join(path, "rootfs"), 0); err != nil {
316 log.G(ctx).WithError(err).Warn("failed to cleanup rootfs mount")
317 }
318 pid, err := runcC.ReadPidFile(filepath.Join(path, process.InitPidFile))
319 if err != nil {
320 log.G(ctx).WithError(err).Warn("failed to read init pid file")
321 }
322 return shim.StopStatus{
323 ExitedAt: time.Now(),
324 ExitStatus: 128 + int(unix.SIGKILL),
325 Pid: pid,
326 }, nil
327 }
328
329 func (m manager) Info(ctx context.Context, optionsR io.Reader) (*types.RuntimeInfo, error) {
330 info := &types.RuntimeInfo{
331 Name: m.name,
332 Version: &types.RuntimeVersion{
333 Version: version.Version,
334 Revision: version.Revision,
335 },
336 Annotations: nil,
337 }
338 binaryName := runcC.DefaultCommand
339 opts, err := shim.ReadRuntimeOptions[*options.Options](optionsR)
340 if err != nil {
341 if !errors.Is(err, errdefs.ErrNotFound) {
342 return nil, fmt.Errorf("failed to read runtime options (*options.Options): %w", err)
343 }
344 }
345 if opts != nil {
346 info.Options, err = typeurl.MarshalAnyToProto(opts)
347 if err != nil {
348 return nil, fmt.Errorf("failed to marshal %T: %w", opts, err)
349 }
350 if opts.BinaryName != "" {
351 binaryName = opts.BinaryName
352 }
353
354 }
355 absBinary, err := exec.LookPath(binaryName)
356 if err != nil {
357 return nil, fmt.Errorf("failed to look up the path of %q: %w", binaryName, err)
358 }
359 features, err := m.features(ctx, absBinary, opts)
360 if err != nil {
361 // youki does not implement `runc features` yet, at the time of writing this (Sep 2023)
362 // https://github.com/containers/youki/issues/815
363 log.G(ctx).WithError(err).Debug("Failed to get the runtime features. The runc binary does not implement `runc features` command?")
364 }
365 if features != nil {
366 info.Features, err = typeurl.MarshalAnyToProto(features)
367 if err != nil {
368 return nil, fmt.Errorf("failed to marshal %T: %w", features, err)
369 }
370 }
371 return info, nil
372 }
373
374 func (m manager) features(ctx context.Context, absBinary string, opts *options.Options) (*features.Features, error) {
375 var stderr bytes.Buffer
376 cmd := exec.CommandContext(ctx, absBinary, "features")
377 cmd.Stderr = &stderr
378 stdout, err := cmd.Output()
379 if err != nil {
380 return nil, fmt.Errorf("failed to execute %v: %w (stderr: %q)", cmd.Args, err, stderr.String())
381 }
382 var feat features.Features
383 if err := json.Unmarshal(stdout, &feat); err != nil {
384 return nil, err
385 }
386 return &feat, nil
387 }