forked from bazel-contrib/rules_img
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanifest.go
More file actions
691 lines (624 loc) · 24.8 KB
/
Copy pathmanifest.go
File metadata and controls
691 lines (624 loc) · 24.8 KB
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
package manifest
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"flag"
"fmt"
"maps"
"os"
"slices"
"strings"
"time"
"github.com/opencontainers/go-digest"
specs "github.com/opencontainers/image-spec/specs-go"
specv1 "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/bazel-contrib/rules_img/img_tool/pkg/api"
"github.com/bazel-contrib/rules_img/img_tool/pkg/kvfile"
)
var (
operatingSystem string
architecture string
variant string
layerFromMetadataArgs fileList
configFragment string
configMediaType string
configTemplates string
baseManifest string
baseConfig string
baseDescriptor string
manifestOutput string
configOutput string
descriptorOutput string
digestOutput string
user string
env stringMap
envFile string
entrypoint stringList
cmd stringList
workingDir string
labels stringMap
annotations stringMap
stopSignal string
created string
artifactType string
subjectDescriptor string
)
func ManifestProcess(_ context.Context, args []string) {
flagSet := flag.NewFlagSet("manifest", flag.ExitOnError)
flagSet.Usage = func() {
fmt.Fprintf(flagSet.Output(), "Creates an OCI image config and manifest based on layers and other metadata.\n\n")
fmt.Fprintf(flagSet.Output(), "Usage: img manifest [--os os] [--architecture arch] [--layer-from-metadata param_file] [--config-fragment config_file] [--base-manifest manifest_file] [--base-config config_file] [--manifest manifest_file] [--config config_file]\n")
flagSet.PrintDefaults()
examples := []string{
"img manifest --os linux --architecture amd64 --layer-from-metadata layer-metadata.json --config-fragment extra-config.json --base-manifest base-manifest.json --base-config base-config.json --manifest manifest.json --config config.json",
}
fmt.Fprintf(flagSet.Output(), "\nExamples:\n")
for _, example := range examples {
fmt.Fprintf(flagSet.Output(), " $ %s\n", example)
}
os.Exit(1)
}
flagSet.StringVar(&operatingSystem, "os", "linux", `The operating system of the image. Defaults to linux.`)
flagSet.StringVar(&architecture, "architecture", "amd64", `The architecture of the image. Defaults to amd64.`)
flagSet.StringVar(&variant, "variant", "", `The platform variant (e.g., v3 for amd64/v3, v8 for arm64/v8).`)
flagSet.Var(&layerFromMetadataArgs, "layer-from-metadata", `Ordered list of layer metadata files that will make up the image, as produced by "img layer --metadata".`)
flagSet.StringVar(&configFragment, "config-fragment", "", `A JSON file containing a config fragment to be merged into the final config. This is useful for adding custom labels or other metadata to the image. When --config-media-type is set to a non-OCI type (e.g. application/vnd.cncf.helm.config.v1+json for Helm), this file is used as the entire config blob as-is.`)
flagSet.StringVar(&configMediaType, "config-media-type", "", `Override the config blob media type. When set to application/vnd.oci.empty.v1+json, --config-fragment is optional; if omitted, an empty JSON config descriptor is produced with inlined data. For other non-OCI types (e.g. application/vnd.cncf.helm.config.v1+json for Helm charts), --config-fragment is required and used verbatim as the config blob with no OCI image structure.`)
flagSet.StringVar(&configTemplates, "config-templates", "", `A JSON file containing template-expanded env, labels, and annotations values.`)
flagSet.StringVar(&baseManifest, "base-manifest", "", `A JSON file containing a base manifest to be merged into the final manifest. This is useful for adding custom layers or other metadata to the image.`)
flagSet.StringVar(&baseConfig, "base-config", "", `A JSON file containing a base config to be merged into the final config. This is useful for adding custom labels or other metadata to the image.`)
flagSet.StringVar(&baseDescriptor, "base-descriptor", "", `A JSON file containing the descriptor of the base manifest.`)
flagSet.StringVar(&manifestOutput, "manifest", "", `The output file for the final manifest.`)
flagSet.StringVar(&configOutput, "config", "", `The output file for the final config.`)
flagSet.StringVar(&descriptorOutput, "descriptor", "", `The output file for the descriptor of the manifest.`)
flagSet.StringVar(&digestOutput, "digest", "", `The (optional) output file for the digest of the manifest. This is useful for postprocessing.`)
flagSet.StringVar(&user, "user", "", `The username or UID which the process in the container should run as.`)
flagSet.Var(&env, "env", `Environment variables to set in the container (can be specified multiple times as key=value).`)
flagSet.StringVar(&envFile, "env-file", "", `A file containing environment variables, as JSON ({"KEY":"value"}, {"KEY":["v1","v2"]}, or ["KEY=value"]) or newline-delimited KEY=VALUE text (blank lines and lines starting with '#' are ignored). Values from --env take precedence over the file.`)
flagSet.Var(&entrypoint, "entrypoint", `Command to execute when the container starts (can be specified multiple times).`)
flagSet.Var(&cmd, "cmd", `Default arguments to the entrypoint (can be specified multiple times).`)
flagSet.StringVar(&workingDir, "working-dir", "", `Working directory inside the container.`)
flagSet.Var(&labels, "label", `Metadata labels for the container (can be specified multiple times as key=value).`)
flagSet.Var(&annotations, "annotation", `Metadata annotations for the manifest (can be specified multiple times as key=value).`)
flagSet.StringVar(&stopSignal, "stop-signal", "", `Signal to stop the container.`)
flagSet.StringVar(&created, "created", "", `A file containing a datetime string (RFC 3339 format) for when the image was created.`)
flagSet.StringVar(&artifactType, "artifact-type", "", `Optional IANA media type of the artifact when the manifest is used for an artifact (e.g. application/vnd.cncf.helm.chart.v1, application/spdx+json).`)
flagSet.StringVar(&subjectDescriptor, "subject-descriptor", "", `A JSON file containing the descriptor of the subject manifest or index.`)
if err := flagSet.Parse(args); err != nil {
flagSet.Usage()
os.Exit(1)
}
if flagSet.NArg() != 0 {
fmt.Fprintf(os.Stderr, "Unexpected positional arguments: %s\n", strings.Join(flagSet.Args(), " "))
flagSet.Usage()
os.Exit(1)
}
if configMediaType != "" && configMediaType != specv1.MediaTypeImageConfig && configMediaType != api.MediaTypeEmptyJSON && configFragment == "" {
fmt.Fprintf(os.Stderr, "--config-media-type %s requires --config-fragment\n", configMediaType)
os.Exit(1)
}
// ARM64 defaults to v8 variant
// See: https://github.com/containerd/platforms/blob/2e51fd9435bd985e1753954b24f4b0453f4e4767/platforms.go#L290
if architecture == "arm64" && variant == "" {
variant = "v8"
}
layers := make([]api.Descriptor, len(layerFromMetadataArgs))
for i, layerFile := range layerFromMetadataArgs {
layer, err := readLayerMetadata(layerFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read layer metadata file %s: %v\n", layerFile, err)
os.Exit(1)
}
layers[i] = layer
}
// Read config templates once if provided
var templatesData *ConfigTemplates
if configTemplates != "" {
var err error
templatesData, err = readConfigTemplates(configTemplates)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read config templates: %v\n", err)
os.Exit(1)
}
}
// Read created timestamp if provided
var createdTime *time.Time
if created != "" {
ct, err := readCreatedTimestamp(created)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read created timestamp: %v\n", err)
os.Exit(1)
}
createdTime = ct
}
var configRaw []byte
if configMediaType == "" {
configMediaType = specv1.MediaTypeImageConfig
config, err := prepareConfig(layers, templatesData, createdTime)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to prepare config: %v\n", err)
os.Exit(1)
}
configRaw, err = json.Marshal(config)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to marshal config: %v\n", err)
os.Exit(1)
}
} else if configMediaType == api.MediaTypeEmptyJSON && configFragment == "" {
// Empty JSON config: "{}" encoded as base64 "e30="
configRaw = []byte("{}")
} else {
// read the config fragment as-is instead of merging it with the base config
// this is useful for non-OCI config media types (e.g. application/vnd.cncf.helm.config.v1+json for Helm charts)
var err error
configRaw, err = os.ReadFile(configFragment)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read config fragment: %v\n", err)
os.Exit(1)
}
}
sha256Hash := sha256.Sum256(configRaw)
layerDescriptors := make([]specv1.Descriptor, len(layers))
for i, layer := range layers {
// While the spec says Docker and OCI layer types SHOULD be fully interchangeable,
// some tools like podman don't allow mixing and matching. For that reason, we
// promote the old Docker type to the new OCI one.
mediaType := layer.MediaType
if mediaType == "application/vnd.docker.image.rootfs.diff.tar.gzip" {
mediaType = api.TarGzipLayer
}
layerDescriptors[i] = specv1.Descriptor{
MediaType: mediaType,
Digest: digest.Digest(layer.Digest),
Size: layer.Size,
Annotations: layer.Annotations,
}
if mediaType == api.MediaTypeEmptyJSON {
layerDescriptors[i].Data = []byte("{}")
}
}
configDescriptor := specv1.Descriptor{
MediaType: configMediaType,
Digest: digest.NewDigestFromBytes(digest.SHA256, sha256Hash[:]),
Size: int64(len(configRaw)),
}
if configMediaType == api.MediaTypeEmptyJSON && configFragment == "" {
configDescriptor.Data = configRaw
}
manifest := specv1.Manifest{
Versioned: specs.Versioned{
SchemaVersion: 2,
},
MediaType: specv1.MediaTypeImageManifest,
ArtifactType: artifactType,
Config: configDescriptor,
Layers: layerDescriptors,
}
// Set subject descriptor if provided
if subjectDescriptor != "" {
subjectData, err := os.ReadFile(subjectDescriptor)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read subject descriptor file %s: %v\n", subjectDescriptor, err)
os.Exit(1)
}
var subjectDesc specv1.Descriptor
if err := json.Unmarshal(subjectData, &subjectDesc); err != nil {
fmt.Fprintf(os.Stderr, "Failed to decode subject descriptor: %v\n", err)
os.Exit(1)
}
manifest.Subject = &subjectDesc
}
// Apply annotations from config templates or command line
annotationsToApply := annotations
if templatesData != nil && templatesData.Annotations != nil {
annotationsToApply = templatesData.Annotations
}
// Set base image digest annotation if we have a base descriptor
annotationsToApply, err := annotationsFromBaseImageDescriptorFile(baseDescriptor, annotationsToApply)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to compute annotations: %v\n", err)
os.Exit(1)
}
if len(annotationsToApply) > 0 {
manifest.Annotations = make(map[string]string)
// Add annotations in sorted order to ensure determinism
keys := make([]string, 0, len(annotationsToApply))
for key := range annotationsToApply {
keys = append(keys, key)
}
slices.Sort(keys)
for _, key := range keys {
manifest.Annotations[key] = annotationsToApply[key]
}
}
manifestRaw, err := json.Marshal(manifest)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to marshal manifest: %v\n", err)
os.Exit(1)
}
manifestSHA256 := sha256.Sum256(manifestRaw)
descriptor := specv1.Descriptor{
MediaType: specv1.MediaTypeImageManifest,
Digest: digest.NewDigestFromBytes(digest.SHA256, manifestSHA256[:]),
Size: int64(len(manifestRaw)),
ArtifactType: artifactType,
Platform: &specv1.Platform{
Architecture: architecture,
OS: operatingSystem,
Variant: variant,
},
Annotations: manifest.Annotations,
}
descriptorRaw, err := json.Marshal(descriptor)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to marshal manifest descriptor: %v\n", err)
os.Exit(1)
}
if manifestOutput != "" {
if err := os.WriteFile(manifestOutput, manifestRaw, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write manifest to %s: %v\n", manifestOutput, err)
os.Exit(1)
}
}
if configOutput != "" {
if err := os.WriteFile(configOutput, configRaw, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write config to %s: %v\n", configOutput, err)
os.Exit(1)
}
}
if descriptorOutput != "" {
if err := os.WriteFile(descriptorOutput, descriptorRaw, 0o644); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write manifest descriptor to %s: %v\n", descriptorOutput, err)
os.Exit(1)
}
}
if digestOutput != "" {
digestFile, err := os.Create(digestOutput)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to create digest file %s: %v\n", digestOutput, err)
os.Exit(1)
}
defer digestFile.Close()
if _, err := fmt.Fprintf(digestFile, "%s", fmt.Sprintf("sha256:%x", manifestSHA256)); err != nil {
fmt.Fprintf(os.Stderr, "Failed to write digest to %s: %v\n", digestOutput, err)
os.Exit(1)
}
}
}
func prepareConfig(layers []api.Descriptor, templatesData *ConfigTemplates, createdTime *time.Time) (specv1.Image, error) {
// first, read the base config
// then, layer the config fragment on top of it
// finally, add our own stuff
var config specv1.Image
if baseConfig != "" {
if err := overlayConfigFromFile(&config, baseConfig, true); err != nil {
return config, fmt.Errorf("reading base config: %w", err)
}
}
if configFragment != "" {
if err := overlayConfigFromFile(&config, configFragment, false); err != nil {
return config, fmt.Errorf("reading config fragment: %w", err)
}
}
if err := overlayNewConfigValues(&config, layers, templatesData); err != nil {
return config, fmt.Errorf("overlaying new config values: %w", err)
}
// Set created timestamp if provided
if createdTime != nil {
config.Created = createdTime
}
for _, layer := range layers {
for _, historyEntry := range layer.History {
config.History = append(config.History, specv1.History{
Created: historyEntry.Created,
CreatedBy: historyEntry.CreatedBy,
Author: historyEntry.Author,
Comment: historyEntry.Comment,
EmptyLayer: historyEntry.EmptyLayer,
})
}
}
return config, nil
}
func readLayerMetadata(filePath string) (api.Descriptor, error) {
file, err := os.Open(filePath)
if err != nil {
return api.Descriptor{}, fmt.Errorf("opening layer metadata file: %w", err)
}
defer file.Close()
var layer api.Descriptor
decoder := json.NewDecoder(file)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&layer); err != nil {
return api.Descriptor{}, fmt.Errorf("decoding layer metadata file: %w", err)
}
return layer, nil
}
func overlayConfigFromFile(config *specv1.Image, filePath string, isBase bool) error {
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("opening config file: %w", err)
}
defer file.Close()
var configFragment specv1.Image
if err := json.NewDecoder(file).Decode(&configFragment); err != nil {
return fmt.Errorf("decoding config file: %w", err)
}
// when merging, we need to perform some checks first
if configFragment.OS != "" && config.OS != "" && configFragment.OS != config.OS {
return fmt.Errorf("OS mismatch: %s != %s", configFragment.OS, config.OS)
}
if configFragment.Architecture != "" && config.Architecture != "" && configFragment.Architecture != config.Architecture {
return fmt.Errorf("architecture mismatch: %s != %s", configFragment.Architecture, config.Architecture)
}
// merge the config fragment into the base config
if configFragment.OS != "" {
config.OS = configFragment.OS
}
if configFragment.Architecture != "" {
config.Architecture = configFragment.Architecture
}
// History is reconstructed from per-layer metadata in prepareConfig; the base
// config's redundant copy is intentionally not merged here, otherwise base
// layers would be counted twice (history longer than rootfs.diff_ids).
// merge config.Config
if configFragment.Config.User != "" {
config.Config.User = configFragment.Config.User
}
if configFragment.Config.ExposedPorts != nil {
// replace the ExposedPorts map
// so that we can unexpose ports
// that were exposed in the underlying config
config.Config.ExposedPorts = maps.Clone(configFragment.Config.ExposedPorts)
}
if configFragment.Config.Env != nil {
// for environment variables, we need to replace items thar are in both
// configs, but append new ones
keysUnderlying := make(map[string]string, len(config.Config.Env))
keysOverlay := make(map[string]string, len(configFragment.Config.Env))
for _, env := range config.Config.Env {
kv := strings.SplitN(env, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("invalid environment variable format: %s (should be key=value)", env)
}
keysUnderlying[kv[0]] = kv[1]
}
for _, env := range configFragment.Config.Env {
kv := strings.SplitN(env, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("invalid environment variable format: %s (should be key=value)", env)
}
keysOverlay[kv[0]] = kv[1]
}
// replace the keys in the underlying config
for i, env := range config.Config.Env {
kv := strings.SplitN(env, "=", 2)
if _, ok := keysOverlay[kv[0]]; ok {
config.Config.Env[i] = fmt.Sprintf("%s=%s", kv[0], keysOverlay[kv[0]])
delete(keysOverlay, kv[0])
}
}
// append the new keys in the original order
for _, env := range configFragment.Config.Env {
kv := strings.SplitN(env, "=", 2)
if _, ok := keysUnderlying[kv[0]]; !ok {
config.Config.Env = append(config.Config.Env, env)
}
}
}
if configFragment.Config.Entrypoint != nil {
config.Config.Entrypoint = slices.Clone(configFragment.Config.Entrypoint)
}
if configFragment.Config.Cmd != nil {
config.Config.Cmd = slices.Clone(configFragment.Config.Cmd)
}
if configFragment.Config.Volumes != nil {
config.Config.Volumes = maps.Clone(configFragment.Config.Volumes)
}
if configFragment.Config.WorkingDir != "" {
config.Config.WorkingDir = configFragment.Config.WorkingDir
}
if configFragment.Config.Labels != nil {
// merge labels
if config.Config.Labels == nil {
config.Config.Labels = maps.Clone(configFragment.Config.Labels)
} else {
maps.Copy(config.Config.Labels, configFragment.Config.Labels)
}
}
if configFragment.Config.StopSignal != "" {
config.Config.StopSignal = configFragment.Config.StopSignal
}
// inherit some fields if this is not a base config
if !isBase {
if !(config.Created == nil) && !configFragment.Created.IsZero() {
config.Created = configFragment.Created
}
if configFragment.Author != "" {
config.Author = configFragment.Author
}
}
return nil
}
func overlayNewConfigValues(config *specv1.Image, layers []api.Descriptor, templatesData *ConfigTemplates) error {
if config.OS != "" && operatingSystem != "" && config.OS != operatingSystem {
return fmt.Errorf("OS mismatch: %s != %s", config.OS, operatingSystem)
}
if config.OS == "" {
config.OS = operatingSystem
}
if config.Architecture != "" && architecture != "" && config.Architecture != architecture {
return fmt.Errorf("architecture mismatch: %s != %s", config.Architecture, architecture)
}
if config.Architecture == "" {
config.Architecture = architecture
}
if config.Variant != "" && variant != "" && config.Variant != variant {
return fmt.Errorf("variant mismatch: %s != %s", config.Variant, variant)
}
if config.Variant == "" {
config.Variant = variant
}
// Set the rootfs struct
config.RootFS.Type = "layers"
config.RootFS.DiffIDs = make([]digest.Digest, len(layers))
for i, layer := range layers {
config.RootFS.DiffIDs[i] = digest.Digest(layer.DiffID)
}
// Apply command-line config values
if user != "" {
config.Config.User = user
}
// Apply environment variables from config templates or command line
envToApply := env
if templatesData != nil && templatesData.Env != nil {
envToApply = templatesData.Env
}
// Merge in environment variables from an env file, if provided.
// Entries from --env / templates take precedence over file entries.
if envFile != "" {
fileEnv, err := readEnvFile(envFile)
if err != nil {
return fmt.Errorf("failed to read env file %s: %w", envFile, err)
}
merged := make(map[string]string, len(fileEnv)+len(envToApply))
maps.Copy(merged, fileEnv)
maps.Copy(merged, envToApply)
envToApply = merged
}
if len(envToApply) > 0 {
// First, build a map of existing env vars
existingEnv := make(map[string]bool)
for i, envVar := range config.Config.Env {
key := strings.SplitN(envVar, "=", 2)[0]
if _, exists := envToApply[key]; exists {
// Update existing env var
config.Config.Env[i] = fmt.Sprintf("%s=%s", key, envToApply[key])
existingEnv[key] = true
}
}
// Add new env vars in sorted order to ensure determinism
keys := make([]string, 0, len(envToApply))
for key := range envToApply {
keys = append(keys, key)
}
slices.Sort(keys)
for _, key := range keys {
if !existingEnv[key] {
config.Config.Env = append(config.Config.Env, fmt.Sprintf("%s=%s", key, envToApply[key]))
}
}
}
// NOTE: Setting entrypoint clears Cmd, which is consistent with Docker/Dockerfile behavior.
// This matches the behavior of rules_oci and crane.
// See: https://github.com/bazel-contrib/rules_img/issues/368
// See: https://github.com/bazel-contrib/rules_oci/issues/649
// See: https://github.com/google/go-containerregistry/blob/c3d1dcc932076c15b65b8b9acfff1d47ded2ebf9/cmd/crane/cmd/mutate.go#L107
if len(entrypoint) > 0 {
config.Config.Entrypoint = []string(entrypoint)
config.Config.Cmd = nil
}
if len(cmd) > 0 {
config.Config.Cmd = []string(cmd)
}
if workingDir != "" {
config.Config.WorkingDir = workingDir
}
// Apply labels from config templates or command line
labelsToApply := labels
if templatesData != nil && templatesData.Labels != nil {
labelsToApply = templatesData.Labels
}
if len(labelsToApply) > 0 {
if config.Config.Labels == nil {
config.Config.Labels = make(map[string]string)
}
// Add labels in sorted order to ensure determinism
keys := make([]string, 0, len(labelsToApply))
for key := range labelsToApply {
keys = append(keys, key)
}
slices.Sort(keys)
for _, key := range keys {
config.Config.Labels[key] = labelsToApply[key]
}
}
if stopSignal != "" {
config.Config.StopSignal = stopSignal
}
return nil
}
// ConfigTemplates represents the structure of the config templates JSON file
type ConfigTemplates struct {
Env map[string]string `json:"env"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
}
// readConfigTemplates reads and parses the config templates JSON file
func readConfigTemplates(filePath string) (*ConfigTemplates, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, fmt.Errorf("opening config templates file: %w", err)
}
defer file.Close()
var templates ConfigTemplates
if err := json.NewDecoder(file).Decode(&templates); err != nil {
return nil, fmt.Errorf("decoding config templates file: %w", err)
}
return &templates, nil
}
// readEnvFile reads a file containing environment variables in JSON or
// newline-delimited KEY=VALUE form (see the kvfile package). Duplicate keys
// keep the last value.
func readEnvFile(filePath string) (map[string]string, error) {
pairs, err := kvfile.ParseFile(filePath)
if err != nil {
return nil, fmt.Errorf("reading env file: %w", err)
}
return kvfile.Flatten(pairs), nil
}
// readCreatedTimestamp reads a file containing a timestamp string and parses it as RFC 3339
func readCreatedTimestamp(filePath string) (*time.Time, error) {
content, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("reading created timestamp file: %w", err)
}
// Trim whitespace from the content
timestampStr := strings.TrimSpace(string(content))
if timestampStr == "" {
return nil, fmt.Errorf("created timestamp file is empty")
}
// Parse as RFC 3339
t, err := time.Parse(time.RFC3339, timestampStr)
if err != nil {
return nil, fmt.Errorf("parsing timestamp as RFC 3339: %w", err)
}
return &t, nil
}
func annotationsFromBaseImageDescriptorFile(filePath string, annotations map[string]string) (map[string]string, error) {
if len(filePath) == 0 {
// We may not have a base image.
return annotations, nil
}
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("reading descriptor file for base image: %w", err)
}
var desc specv1.Descriptor
if err := json.Unmarshal(data, &desc); err != nil {
return nil, fmt.Errorf("decoding descriptor file for base image: %w", err)
}
digest := desc.Digest.String()
if len(digest) == 0 {
return nil, errors.New("decoding descriptor file for base image: expected digest to be set")
}
if annotations == nil {
annotations = make(map[string]string)
}
if _, exists := annotations["org.opencontainers.image.base.digest"]; !exists {
annotations["org.opencontainers.image.base.digest"] = digest
}
return annotations, nil
}