|
| 1 | +// Copyright (c) 2023-2026, Nubificus LTD |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package containerd |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "encoding/json" |
| 20 | + "fmt" |
| 21 | + "io" |
| 22 | + "os" |
| 23 | + "path/filepath" |
| 24 | + "strings" |
| 25 | + |
| 26 | + contentapi "github.com/containerd/containerd/api/services/content/v1" |
| 27 | + imagesapi "github.com/containerd/containerd/api/services/images/v1" |
| 28 | + typesapi "github.com/containerd/containerd/api/types" |
| 29 | + "github.com/containerd/containerd/images" |
| 30 | + |
| 31 | + imagespec "github.com/opencontainers/image-spec/specs-go/v1" |
| 32 | + runtimespec "github.com/opencontainers/runtime-spec/specs-go" |
| 33 | +) |
| 34 | + |
| 35 | +const uruncPrefix = "com.urunc.unikernel." |
| 36 | + |
| 37 | +type annotationFetcher struct { |
| 38 | + containerLabels map[string]string |
| 39 | + contentClient contentapi.ContentClient |
| 40 | + namespace string |
| 41 | + target *typesapi.Descriptor |
| 42 | +} |
| 43 | + |
| 44 | +func newAnnotationFetcher(ctx context.Context, session *Session) (*annotationFetcher, error) { |
| 45 | + container := session.GetContainer() |
| 46 | + if container == nil { |
| 47 | + return nil, fmt.Errorf("container metadata is not loaded") |
| 48 | + } |
| 49 | + |
| 50 | + fetcher := &annotationFetcher{ |
| 51 | + containerLabels: container.Labels, |
| 52 | + contentClient: session.contentClient(), |
| 53 | + namespace: session.GetNamespace(), |
| 54 | + } |
| 55 | + |
| 56 | + if container.Image == "" { |
| 57 | + // TODO: Add Docker fallback. When Docker does not use containerd's image/content |
| 58 | + // store, the containerd container metadata may not include an image reference. |
| 59 | + // In that case, resolve the image reference through the Docker Engine API and |
| 60 | + // fetch manifest annotations from a Docker-compatible path. |
| 61 | + return fetcher, nil |
| 62 | + } |
| 63 | + |
| 64 | + imageResp, err := session.imagesClient().Get( |
| 65 | + withNamespace(ctx, session.GetNamespace()), |
| 66 | + &imagesapi.GetImageRequest{Name: container.Image}, |
| 67 | + ) |
| 68 | + if err != nil { |
| 69 | + return fetcher, nil |
| 70 | + } |
| 71 | + |
| 72 | + fetcher.target = imageResp.GetImage().GetTarget() |
| 73 | + return fetcher, nil |
| 74 | +} |
| 75 | + |
| 76 | +func InjectUruncAnnotations(ctx context.Context, session *Session, bundlePath string) error { |
| 77 | + fetcher, err := newAnnotationFetcher(ctx, session) |
| 78 | + if err != nil { |
| 79 | + return fmt.Errorf("create annotation fetcher: %w", err) |
| 80 | + } |
| 81 | + annotations, err := fetcher.fetchUruncAnnotations(ctx) |
| 82 | + if err != nil { |
| 83 | + return fmt.Errorf("fetch urunc annotations: %w", err) |
| 84 | + } |
| 85 | + if len(annotations) == 0 { |
| 86 | + return nil |
| 87 | + } |
| 88 | + |
| 89 | + return patchConfigJSON(bundlePath, annotations) |
| 90 | +} |
| 91 | + |
| 92 | +func (f *annotationFetcher) fetchUruncAnnotations(ctx context.Context) (map[string]string, error) { |
| 93 | + filtered := make(map[string]string) |
| 94 | + |
| 95 | + // Collect urunc annotations from container labels. |
| 96 | + for k, v := range f.containerLabels { |
| 97 | + if strings.HasPrefix(k, uruncPrefix) { |
| 98 | + filtered[k] = v |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + // Collect urunc annotations from manifest |
| 103 | + if f.target == nil || !images.IsManifestType(f.target.MediaType) { |
| 104 | + // If the image target is missing or does not point to a manifest, |
| 105 | + // keep the labels collected so far. |
| 106 | + return filtered, nil |
| 107 | + } |
| 108 | + |
| 109 | + manifestRaw, err := readBlob(ctx, f.namespace, f.contentClient, f.target.Digest, f.target.Size) |
| 110 | + if err != nil { |
| 111 | + return nil, fmt.Errorf("read manifest blob: %w", err) |
| 112 | + } |
| 113 | + |
| 114 | + var manifest imagespec.Manifest |
| 115 | + if err := json.Unmarshal(manifestRaw, &manifest); err != nil { |
| 116 | + return nil, fmt.Errorf("unmarshal manifest: %w", err) |
| 117 | + } |
| 118 | + |
| 119 | + // Manifest annotations override config labels on duplicate keys. |
| 120 | + for k, v := range manifest.Annotations { |
| 121 | + if strings.HasPrefix(k, uruncPrefix) { |
| 122 | + filtered[k] = v |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + return filtered, nil |
| 127 | +} |
| 128 | + |
| 129 | +// readBlob reads a blob with the given digest from containerd's content store |
| 130 | +// and returns it as a byte slice. |
| 131 | +func readBlob(ctx context.Context, namespace string, contentClient contentapi.ContentClient, digest string, size int64) ([]byte, error) { |
| 132 | + stream, err := contentClient.Read(withNamespace(ctx, namespace), &contentapi.ReadContentRequest{ |
| 133 | + Digest: digest, |
| 134 | + Size: size, |
| 135 | + }) |
| 136 | + if err != nil { |
| 137 | + return nil, containerdErr(err) |
| 138 | + } |
| 139 | + |
| 140 | + var raw []byte |
| 141 | + for { |
| 142 | + resp, err := stream.Recv() |
| 143 | + if err == io.EOF { |
| 144 | + break |
| 145 | + } |
| 146 | + if err != nil { |
| 147 | + return nil, containerdErr(err) |
| 148 | + } |
| 149 | + raw = append(raw, resp.Data...) |
| 150 | + } |
| 151 | + |
| 152 | + return raw, nil |
| 153 | +} |
| 154 | + |
| 155 | +// patchConfigJSON injects missing annotations into the OCI runtime spec |
| 156 | +// stored in the bundle's config.json. |
| 157 | +// |
| 158 | +// Existing annotations in config.json are preserved. Only annotation keys that |
| 159 | +// are not already present in the runtime spec are added. |
| 160 | +func patchConfigJSON(bundlePath string, annotations map[string]string) error { |
| 161 | + configPath := filepath.Join(bundlePath, "config.json") |
| 162 | + |
| 163 | + fi, err := os.Stat(configPath) |
| 164 | + if err != nil { |
| 165 | + return fmt.Errorf("stat config.json: %w", err) |
| 166 | + } |
| 167 | + |
| 168 | + data, err := os.ReadFile(configPath) |
| 169 | + if err != nil { |
| 170 | + return fmt.Errorf("read config.json: %w", err) |
| 171 | + } |
| 172 | + |
| 173 | + var spec runtimespec.Spec |
| 174 | + if err := json.Unmarshal(data, &spec); err != nil { |
| 175 | + return fmt.Errorf("unmarshal spec: %w", err) |
| 176 | + } |
| 177 | + |
| 178 | + if spec.Annotations == nil { |
| 179 | + spec.Annotations = make(map[string]string) |
| 180 | + } |
| 181 | + |
| 182 | + for k, v := range annotations { |
| 183 | + if _, exists := spec.Annotations[k]; exists { |
| 184 | + continue |
| 185 | + } |
| 186 | + spec.Annotations[k] = v |
| 187 | + } |
| 188 | + |
| 189 | + patched, err := json.MarshalIndent(spec, "", " ") |
| 190 | + if err != nil { |
| 191 | + return fmt.Errorf("marshal spec: %w", err) |
| 192 | + } |
| 193 | + |
| 194 | + if err := atomicWriteFile(configPath, patched, fi.Mode()); err != nil { |
| 195 | + return fmt.Errorf("write config.json atomically: %w", err) |
| 196 | + } |
| 197 | + return nil |
| 198 | +} |
| 199 | + |
| 200 | +func atomicWriteFile(path string, data []byte, mode os.FileMode) error { |
| 201 | + tmpDir := filepath.Dir(path) |
| 202 | + |
| 203 | + f, err := os.CreateTemp(tmpDir, "."+filepath.Base(path)+".tmp-*") |
| 204 | + if err != nil { |
| 205 | + return err |
| 206 | + } |
| 207 | + |
| 208 | + tmpName := f.Name() |
| 209 | + defer os.Remove(tmpName) |
| 210 | + |
| 211 | + if err := f.Chmod(mode); err != nil { |
| 212 | + _ = f.Close() |
| 213 | + return err |
| 214 | + } |
| 215 | + |
| 216 | + if _, err := f.Write(data); err != nil { |
| 217 | + _ = f.Close() |
| 218 | + return err |
| 219 | + } |
| 220 | + |
| 221 | + if err := f.Sync(); err != nil { |
| 222 | + _ = f.Close() |
| 223 | + return err |
| 224 | + } |
| 225 | + |
| 226 | + if err := f.Close(); err != nil { |
| 227 | + return err |
| 228 | + } |
| 229 | + |
| 230 | + if err := os.Rename(tmpName, path); err != nil { |
| 231 | + return err |
| 232 | + } |
| 233 | + |
| 234 | + return nil |
| 235 | +} |
0 commit comments