github.com/moby/docker@v26.1.3+incompatible/internal/testutils/specialimage/random.go (about) 1 package specialimage 2 3 import ( 4 "math/rand" 5 "strconv" 6 7 "github.com/distribution/reference" 8 "github.com/opencontainers/go-digest" 9 ocispec "github.com/opencontainers/image-spec/specs-go/v1" 10 ) 11 12 func RandomSinglePlatform(dir string, platform ocispec.Platform, source rand.Source) (*ocispec.Index, error) { 13 r := rand.New(source) //nolint:gosec // Ignore G404: Use of weak random number generator (math/rand instead of crypto/rand) 14 15 imageRef := "random-" + strconv.FormatInt(r.Int63(), 10) + ":latest" 16 17 layerCount := r.Intn(8) 18 19 var layers []ocispec.Descriptor 20 for i := 0; i < layerCount; i++ { 21 layerDesc, err := writeLayerWithOneFile(dir, "layer-"+strconv.Itoa(i), []byte(strconv.Itoa(i))) 22 if err != nil { 23 return nil, err 24 } 25 layers = append(layers, layerDesc) 26 } 27 28 configDesc, err := writeJsonBlob(dir, ocispec.MediaTypeImageConfig, ocispec.Image{ 29 Platform: platform, 30 Config: ocispec.ImageConfig{ 31 Env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, 32 }, 33 RootFS: ocispec.RootFS{ 34 Type: "layers", 35 DiffIDs: layersToDigests(layers), 36 }, 37 }) 38 if err != nil { 39 return nil, err 40 } 41 42 manifest := ocispec.Manifest{ 43 MediaType: ocispec.MediaTypeImageManifest, 44 Config: configDesc, 45 Layers: layers, 46 } 47 48 legacyManifests := []manifestItem{ 49 { 50 Config: blobPath(configDesc), 51 RepoTags: []string{imageRef}, 52 Layers: blobPaths(layers), 53 }, 54 } 55 56 ref, err := reference.ParseNormalizedNamed(imageRef) 57 if err != nil { 58 return nil, err 59 } 60 return singlePlatformImage(dir, ref, manifest, legacyManifests) 61 } 62 63 func layersToDigests(layers []ocispec.Descriptor) []digest.Digest { 64 var digests []digest.Digest 65 for _, l := range layers { 66 digests = append(digests, l.Digest) 67 } 68 return digests 69 } 70 71 func blobPaths(descriptors []ocispec.Descriptor) []string { 72 var paths []string 73 for _, d := range descriptors { 74 paths = append(paths, blobPath(d)) 75 } 76 return paths 77 }