blob: 0c6d4974160a5d2539a979fd0ab3634b8c92bf9b [file] [log] [blame]
Lorenz Brunc88c82d2020-05-08 14:35:04 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package containerd
18
19import (
20 "context"
Lorenz Brun878f5f92020-05-12 16:15:39 +020021 "fmt"
Lorenz Brun6acfc322020-05-13 17:01:26 +020022 "io"
Lorenz Brun8b0431a2020-07-13 16:56:36 +020023 "io/ioutil"
Lorenz Brunc88c82d2020-05-08 14:35:04 +020024 "os"
25 "os/exec"
Lorenz Brun8b0431a2020-07-13 16:56:36 +020026 "path/filepath"
Lorenz Brun6acfc322020-05-13 17:01:26 +020027 "time"
28
Lorenz Brun8b0431a2020-07-13 16:56:36 +020029 ctr "github.com/containerd/containerd"
30 "github.com/containerd/containerd/namespaces"
31 "go.uber.org/zap"
32
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020033 "git.monogon.dev/source/nexantic.git/core/internal/localstorage"
Lorenz Brun8b0431a2020-07-13 16:56:36 +020034
35 "git.monogon.dev/source/nexantic.git/core/internal/common/supervisor"
Lorenz Brunc88c82d2020-05-08 14:35:04 +020036 "git.monogon.dev/source/nexantic.git/core/pkg/logbuffer"
Lorenz Brunc88c82d2020-05-08 14:35:04 +020037)
38
Lorenz Brun8b0431a2020-07-13 16:56:36 +020039const (
40 preseedNamespacesDir = "/containerd/preseed/"
41)
42
Lorenz Brun878f5f92020-05-12 16:15:39 +020043type Service struct {
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020044 EphemeralVolume *localstorage.EphemeralContainerdDirectory
Lorenz Brun8b0431a2020-07-13 16:56:36 +020045 Log *logbuffer.LogBuffer
46 RunscLog *logbuffer.LogBuffer
Lorenz Brun878f5f92020-05-12 16:15:39 +020047}
Lorenz Brunc88c82d2020-05-08 14:35:04 +020048
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020049func (s *Service) Run(ctx context.Context) error {
50 if s.Log == nil {
51 s.Log = logbuffer.New(5000, 16384)
52 }
53 if s.RunscLog == nil {
54 s.RunscLog = logbuffer.New(5000, 16384)
55 }
Lorenz Brunc88c82d2020-05-08 14:35:04 +020056
Lorenz Brun8b0431a2020-07-13 16:56:36 +020057 logger := supervisor.Logger(ctx)
58
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020059 cmd := exec.CommandContext(ctx, "/containerd/bin/containerd", "--config", "/containerd/conf/config.toml")
60 cmd.Stdout = s.Log
61 cmd.Stderr = s.Log
62 cmd.Env = []string{"PATH=/containerd/bin", "TMPDIR=" + s.EphemeralVolume.Tmp.FullPath()}
Lorenz Brun878f5f92020-05-12 16:15:39 +020063
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020064 runscFifo, err := os.OpenFile(s.EphemeralVolume.RunSCLogsFIFO.FullPath(), os.O_CREATE|os.O_RDONLY, os.ModeNamedPipe|0777)
65 if err != nil {
Lorenz Brun878f5f92020-05-12 16:15:39 +020066 return err
Lorenz Brunc88c82d2020-05-08 14:35:04 +020067 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020068 go func() {
69 for {
70 n, err := io.Copy(s.RunscLog, runscFifo)
71 if n == 0 && err == nil {
72 // Hack because pipes/FIFOs can return zero reads when nobody is writing. To avoid busy-looping,
73 // sleep a bit before retrying. This does not loose data since the FIFO internal buffer will
74 // stall writes when it becomes full. 10ms maximum stall in a non-latency critical process (reading
75 // debug logs) is not an issue for us.
76 time.Sleep(10 * time.Millisecond)
77 } else if err != nil {
Lorenz Brun8b0431a2020-07-13 16:56:36 +020078 logger.Error("gVisor log pump failed, stopping it", zap.Error(err))
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020079 return // It's likely that this will busy-loop printing errors if it encounters one, so bail
80 }
81 }
82 }()
83
Lorenz Brun8b0431a2020-07-13 16:56:36 +020084 if err := supervisor.Run(ctx, "preseed", s.runPreseed); err != nil {
85 return fmt.Errorf("failed to start preseed runnable: %w", err)
86 }
87 supervisor.Signal(ctx, supervisor.SignalHealthy)
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020088
89 err = cmd.Run()
90 fmt.Fprintf(s.Log, "containerd stopped: %v\n", err)
91 return err
Lorenz Brunc88c82d2020-05-08 14:35:04 +020092}
Lorenz Brun8b0431a2020-07-13 16:56:36 +020093
94// runPreseed loads OCI bundles in tar form from preseedNamespacesDir into containerd at startup.
95// This can be run multiple times, containerd will automatically dedup the layers.
96// containerd uses namespaces to keep images (and everything else) separate so to define where the images will be loaded
97// to they need to be in a folder named after the namespace they should be loaded into.
98// containerd's CRI plugin (which is built as part of containerd) uses a hardcoded namespace ("k8s.io") for everything
99// accessed through CRI, so if an image should be available on K8s it needs to be in that namespace.
100// As an example if image helloworld should be loaded for use with Kubernetes, the OCI bundle needs to be at
101// <preseedNamespacesDir>/k8s.io/helloworld.tar. No tagging beyond what's in the bundle is performed.
102func (s *Service) runPreseed(ctx context.Context) error {
103 client, err := ctr.New(s.EphemeralVolume.ClientSocket.FullPath())
104 if err != nil {
105 return fmt.Errorf("failed to connect to containerd: %w", err)
106 }
107 logger := supervisor.Logger(ctx)
108 preseedNamespaceDirs, err := ioutil.ReadDir(preseedNamespacesDir)
109 if err != nil {
110 return fmt.Errorf("failed to open preseed dir: %w", err)
111 }
112 for _, dir := range preseedNamespaceDirs {
113 if !dir.IsDir() {
114 logger.Warn("Non-Directory found in preseed folder, ignoring", zap.String("name", dir.Name()))
115 continue
116 }
117 namespace := dir.Name()
118 images, err := ioutil.ReadDir(filepath.Join(preseedNamespacesDir, namespace))
119 if err != nil {
120 return fmt.Errorf("failed to list namespace preseed directory for ns \"%v\": %w", namespace, err)
121 }
122 ctxWithNS := namespaces.WithNamespace(ctx, namespace)
123 for _, image := range images {
124 if image.IsDir() {
125 logger.Warn("Directory found in preseed namespaced folder, ignoring", zap.String("name", image.Name()))
126 continue
127 }
128 imageFile, err := os.Open(filepath.Join(preseedNamespacesDir, namespace, image.Name()))
129 if err != nil {
130 return fmt.Errorf("failed to open preseed image \"%v\": %w", image.Name(), err)
131 }
132 // defer in this loop is fine since we're never going to preseed more than ~1M images which is where our
133 // file descriptor limit is.
134 defer imageFile.Close()
135 importedImages, err := client.Import(ctxWithNS, imageFile)
136 if err != nil {
137 return fmt.Errorf("failed to import preseed image: %w", err)
138 }
139 var importedImageNames []string
140 for _, img := range importedImages {
141 importedImageNames = append(importedImageNames, img.Name)
142 }
143 logger.Info("Successfully imported preseeded bundle into containerd",
144 zap.String("namespace", namespace), zap.Strings("images", importedImageNames))
145 }
146 }
147 supervisor.Signal(ctx, supervisor.SignalHealthy)
148 supervisor.Signal(ctx, supervisor.SignalDone)
149 return nil
150}