blob: 192039ef2c91bb8be62001329efaa754253d5609 [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"
Serge Bazanskic7359672020-10-30 16:38:57 +010027 "strings"
Lorenz Brun6acfc322020-05-13 17:01:26 +020028 "time"
29
Lorenz Brun8b0431a2020-07-13 16:56:36 +020030 ctr "github.com/containerd/containerd"
31 "github.com/containerd/containerd/namespaces"
Lorenz Brun8b0431a2020-07-13 16:56:36 +020032
33 "git.monogon.dev/source/nexantic.git/core/internal/common/supervisor"
Serge Bazanskic7359672020-10-30 16:38:57 +010034 "git.monogon.dev/source/nexantic.git/core/internal/localstorage"
Lorenz Brunc88c82d2020-05-08 14:35:04 +020035 "git.monogon.dev/source/nexantic.git/core/pkg/logbuffer"
Lorenz Brunc88c82d2020-05-08 14:35:04 +020036)
37
Lorenz Brun8b0431a2020-07-13 16:56:36 +020038const (
39 preseedNamespacesDir = "/containerd/preseed/"
40)
41
Lorenz Brun878f5f92020-05-12 16:15:39 +020042type Service struct {
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020043 EphemeralVolume *localstorage.EphemeralContainerdDirectory
Lorenz Brun8b0431a2020-07-13 16:56:36 +020044 Log *logbuffer.LogBuffer
45 RunscLog *logbuffer.LogBuffer
Lorenz Brun878f5f92020-05-12 16:15:39 +020046}
Lorenz Brunc88c82d2020-05-08 14:35:04 +020047
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020048func (s *Service) Run(ctx context.Context) error {
49 if s.Log == nil {
50 s.Log = logbuffer.New(5000, 16384)
51 }
52 if s.RunscLog == nil {
53 s.RunscLog = logbuffer.New(5000, 16384)
54 }
Lorenz Brunc88c82d2020-05-08 14:35:04 +020055
Lorenz Brun8b0431a2020-07-13 16:56:36 +020056 logger := supervisor.Logger(ctx)
57
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020058 cmd := exec.CommandContext(ctx, "/containerd/bin/containerd", "--config", "/containerd/conf/config.toml")
59 cmd.Stdout = s.Log
60 cmd.Stderr = s.Log
61 cmd.Env = []string{"PATH=/containerd/bin", "TMPDIR=" + s.EphemeralVolume.Tmp.FullPath()}
Lorenz Brun878f5f92020-05-12 16:15:39 +020062
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020063 runscFifo, err := os.OpenFile(s.EphemeralVolume.RunSCLogsFIFO.FullPath(), os.O_CREATE|os.O_RDONLY, os.ModeNamedPipe|0777)
64 if err != nil {
Lorenz Brun878f5f92020-05-12 16:15:39 +020065 return err
Lorenz Brunc88c82d2020-05-08 14:35:04 +020066 }
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020067 go func() {
68 for {
69 n, err := io.Copy(s.RunscLog, runscFifo)
70 if n == 0 && err == nil {
71 // Hack because pipes/FIFOs can return zero reads when nobody is writing. To avoid busy-looping,
72 // sleep a bit before retrying. This does not loose data since the FIFO internal buffer will
73 // stall writes when it becomes full. 10ms maximum stall in a non-latency critical process (reading
74 // debug logs) is not an issue for us.
75 time.Sleep(10 * time.Millisecond)
76 } else if err != nil {
Serge Bazanskic7359672020-10-30 16:38:57 +010077 logger.Errorf("gVisor log pump failed, stopping it: %v", err)
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020078 return // It's likely that this will busy-loop printing errors if it encounters one, so bail
79 }
80 }
81 }()
82
Lorenz Brun8b0431a2020-07-13 16:56:36 +020083 if err := supervisor.Run(ctx, "preseed", s.runPreseed); err != nil {
84 return fmt.Errorf("failed to start preseed runnable: %w", err)
85 }
86 supervisor.Signal(ctx, supervisor.SignalHealthy)
Serge Bazanskic2c7ad92020-07-13 17:20:09 +020087
88 err = cmd.Run()
89 fmt.Fprintf(s.Log, "containerd stopped: %v\n", err)
90 return err
Lorenz Brunc88c82d2020-05-08 14:35:04 +020091}
Lorenz Brun8b0431a2020-07-13 16:56:36 +020092
93// runPreseed loads OCI bundles in tar form from preseedNamespacesDir into containerd at startup.
94// This can be run multiple times, containerd will automatically dedup the layers.
95// containerd uses namespaces to keep images (and everything else) separate so to define where the images will be loaded
96// to they need to be in a folder named after the namespace they should be loaded into.
97// containerd's CRI plugin (which is built as part of containerd) uses a hardcoded namespace ("k8s.io") for everything
98// accessed through CRI, so if an image should be available on K8s it needs to be in that namespace.
99// As an example if image helloworld should be loaded for use with Kubernetes, the OCI bundle needs to be at
100// <preseedNamespacesDir>/k8s.io/helloworld.tar. No tagging beyond what's in the bundle is performed.
101func (s *Service) runPreseed(ctx context.Context) error {
102 client, err := ctr.New(s.EphemeralVolume.ClientSocket.FullPath())
103 if err != nil {
104 return fmt.Errorf("failed to connect to containerd: %w", err)
105 }
106 logger := supervisor.Logger(ctx)
107 preseedNamespaceDirs, err := ioutil.ReadDir(preseedNamespacesDir)
108 if err != nil {
109 return fmt.Errorf("failed to open preseed dir: %w", err)
110 }
111 for _, dir := range preseedNamespaceDirs {
112 if !dir.IsDir() {
Serge Bazanskic7359672020-10-30 16:38:57 +0100113 logger.Warningf("Non-Directory %q found in preseed folder, ignoring", dir.Name())
Lorenz Brun8b0431a2020-07-13 16:56:36 +0200114 continue
115 }
116 namespace := dir.Name()
117 images, err := ioutil.ReadDir(filepath.Join(preseedNamespacesDir, namespace))
118 if err != nil {
119 return fmt.Errorf("failed to list namespace preseed directory for ns \"%v\": %w", namespace, err)
120 }
121 ctxWithNS := namespaces.WithNamespace(ctx, namespace)
122 for _, image := range images {
123 if image.IsDir() {
Serge Bazanskic7359672020-10-30 16:38:57 +0100124 logger.Warningf("Directory %q found in preseed namespaced folder, ignoring", image.Name())
Lorenz Brun8b0431a2020-07-13 16:56:36 +0200125 continue
126 }
127 imageFile, err := os.Open(filepath.Join(preseedNamespacesDir, namespace, image.Name()))
128 if err != nil {
129 return fmt.Errorf("failed to open preseed image \"%v\": %w", image.Name(), err)
130 }
131 // defer in this loop is fine since we're never going to preseed more than ~1M images which is where our
132 // file descriptor limit is.
133 defer imageFile.Close()
134 importedImages, err := client.Import(ctxWithNS, imageFile)
135 if err != nil {
136 return fmt.Errorf("failed to import preseed image: %w", err)
137 }
138 var importedImageNames []string
139 for _, img := range importedImages {
140 importedImageNames = append(importedImageNames, img.Name)
141 }
Serge Bazanskic7359672020-10-30 16:38:57 +0100142 logger.Infof("Successfully imported preseeded bundle %s/%s into containerd", namespace, strings.Join(importedImageNames, ","))
Lorenz Brun8b0431a2020-07-13 16:56:36 +0200143 }
144 }
145 supervisor.Signal(ctx, supervisor.SignalHealthy)
146 supervisor.Signal(ctx, supervisor.SignalDone)
147 return nil
148}