showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
images.go
8.4 KB · 270 lines
1package build23import (4 "cmp"5 "context"6 "errors"7 "maps"8 "net/url"9 "slices"10 "strings"11 "time"1213 "daum.dev/showcase/internal/gitea"14)1516const (17 maxImageTags = 30 // tags whose manifests are fetched18 maxImageVersions = 8 // distinct digests shown19)2021// ImageView is one container image on the packages page, read from the22// registry. Versions are distinct digests, newest first, each with every23// tag that points at it.24type ImageView struct {25 Name, Ref string // "repo-a", "daum.dev/daniel/repo-a"26 Pull string // docker pull of the newest tag27 Versions []ImageVersion28 More int // digests not shown29 Missing bool30}3132type ImageVersion struct {33 Tags []string34 Digest string35 Kind string // "OCI index", "Docker image", …36 Created time.Time37 Pull string // docker pull by digest38 Platforms []ImagePlatform39 Meta []Meta40}4142type ImagePlatform struct {43 Name string // linux/arm64/v844 Digest string45 Size int64 // config plus compressed layers, what a pull downloads46 Layers int47 Distro string // from os-release, "" if none48 Created time.Time49 config *gitea.ImageConfig50}5152// Meta is one line of image metadata. Href is set for safe links only.53type Meta struct{ Key, Value, Href string }5455var mediaKinds = map[string]string{56 "application/vnd.oci.image.index.v1+json": "OCI index",57 "application/vnd.docker.distribution.manifest.list.v2+json": "Docker manifest list",58 "application/vnd.oci.image.manifest.v1+json": "OCI image",59 "application/vnd.docker.distribution.manifest.v2+json": "Docker image",60}6162// images lists the allowlisted images shown on a repo's packages page: the63// image named like the repo, plus container packages the API links to it.64// Registry trouble never fails the build; the image is shown without details.65func (b *Builder) images(ctx context.Context, r *repo) []ImageView {66 names := []string{}67 if b.Cfg.HasImage(r.Name) {68 names = append(names, r.Name)69 }70 for _, p := range r.Packages {71 if p.Type == "container" && b.Cfg.HasImage(p.Name) && !slices.Contains(names, p.Name) {72 names = append(names, p.Name)73 }74 }75 var out []ImageView76 for _, n := range names {77 ref := siteHost(b.Cfg.SiteURL) + "/" + b.Cfg.User + "/" + n78 v := ImageView{Name: n, Ref: ref, Pull: "docker pull " + ref}79 if err := b.loadImage(ctx, r, &v); err != nil {80 b.Log.Warn("image details", "image", n, "err", err)81 v.Missing, v.Versions, v.More = true, nil, 082 }83 out = append(out, v)84 }85 return out86}8788func (b *Builder) loadImage(ctx context.Context, r *repo, v *ImageView) error {89 reg, err := b.Gitea.Registry(ctx, v.Name)90 if err != nil {91 return err92 }93 tags, err := reg.Tags(ctx)94 if err != nil {95 return err96 }97 slices.Sort(tags)98 byDigest := map[string]*ImageVersion{}99 for _, tag := range tags[:min(len(tags), maxImageTags)] {100 m, digest, err := reg.Manifest(ctx, tag)101 if err != nil {102 return err103 }104 if ver, ok := byDigest[digest]; ok {105 ver.Tags = append(ver.Tags, tag)106 continue107 }108 ver := &ImageVersion{Tags: []string{tag}, Digest: digest, Kind: cmp.Or(mediaKinds[m.MediaType], "image"), Pull: "docker pull " + v.Ref + "@" + digest}109 byDigest[digest] = ver110 descs := []gitea.Descriptor{{Digest: digest}} // a single image: itself111 if len(m.Manifests) > 0 {112 descs = m.Manifests113 }114 for _, d := range descs {115 if d.Platform != nil && (d.Platform.OS == "unknown" || d.Annotations["vnd.docker.reference.type"] != "") {116 continue // build attestations, not runnable images117 }118 p, err := b.platform(ctx, reg, d, m)119 if err != nil {120 return err121 }122 ver.Platforms = append(ver.Platforms, p)123 if p.Created.After(ver.Created) {124 ver.Created = p.Created125 }126 }127 if len(ver.Platforms) > 0 {128 ver.Meta = b.imageMeta(r, ver.Platforms[0].config, reg.RealmHost)129 }130 }131 for _, ver := range byDigest {132 slices.SortFunc(ver.Tags, func(a, c string) int { // latest first, then newest-looking133 return cmp.Or(cmp.Compare(boolInt(c == "latest"), boolInt(a == "latest")), strings.Compare(c, a))134 })135 v.Versions = append(v.Versions, *ver)136 }137 slices.SortFunc(v.Versions, func(a, c ImageVersion) int {138 return cmp.Or(c.Created.Compare(a.Created), strings.Compare(a.Tags[0], c.Tags[0]))139 })140 if len(v.Versions) > maxImageVersions {141 v.Versions, v.More = v.Versions[:maxImageVersions], len(v.Versions)-maxImageVersions142 }143 if len(v.Versions) > 0 {144 v.Pull += ":" + v.Versions[0].Tags[0]145 }146 return nil147}148149func boolInt(b bool) int {150 if b {151 return 1152 }153 return 0154}155156// platform loads one runnable image. Everything it reads is addressed by157// digest, so results are cached for the life of the process.158func (b *Builder) platform(ctx context.Context, reg *gitea.Registry, d gitea.Descriptor, top *gitea.Manifest) (ImagePlatform, error) {159 if p, ok := b.st.images[d.Digest]; ok {160 return p, nil161 }162 m := top163 if len(top.Manifests) > 0 {164 var err error165 if m, _, err = reg.Manifest(ctx, d.Digest); err != nil {166 return ImagePlatform{}, err167 }168 }169 cfg, err := reg.Config(ctx, m.Config)170 if err != nil {171 return ImagePlatform{}, err172 }173 p := ImagePlatform{Digest: d.Digest, Layers: len(m.Layers), Size: m.Config.Size, Created: cfg.Created, config: cfg}174 p.Name = strings.Join(slices.DeleteFunc([]string{cfg.OS, cfg.Architecture, cfg.Variant}, func(s string) bool { return s == "" }), "/")175 for _, l := range m.Layers {176 p.Size += l.Size177 }178 for _, l := range m.Layers[:min(len(m.Layers), 3)] { // the base OS is in the first layers179 distro, err := reg.OSRelease(ctx, l)180 if err == nil {181 p.Distro = distro182 break183 }184 if !errors.Is(err, gitea.ErrNoOSRelease) {185 return ImagePlatform{}, err186 }187 }188 if b.st.images == nil {189 b.st.images = map[string]ImagePlatform{}190 }191 b.st.images[d.Digest] = p192 return p, nil193}194195var labelMeta = []struct{ label, key string }{196 {"org.opencontainers.image.version", "Version"},197 {"org.opencontainers.image.revision", "Revision"},198 {"org.opencontainers.image.base.name", "Base image"},199 {"org.opencontainers.image.licenses", "Licenses"},200 {"org.opencontainers.image.authors", "Authors"},201 {"org.opencontainers.image.vendor", "Vendor"},202 {"org.opencontainers.image.description", "Description"},203 {"org.opencontainers.image.source", "Source"},204 {"org.opencontainers.image.url", "URL"},205 {"org.opencontainers.image.documentation", "Documentation"},206}207208// imageMeta picks the known OCI labels and the runtime settings worth209// showing. Gitea's hosts (the configured one and its ROOT_URL from the210// registry challenge, often a tailnet name) are private: a link to an211// allowlisted repo there points at its page here instead, and any other212// value naming them, or a .ts.net name, is dropped. Only https links are213// linked.214func (b *Builder) imageMeta(r *repo, c *gitea.ImageConfig, realmHost string) []Meta {215 var hosts []string216 if u, err := url.Parse(b.Cfg.GiteaURL); err == nil && u.Hostname() != "" {217 hosts = append(hosts, u.Hostname())218 }219 if realmHost != "" {220 hosts = append(hosts, realmHost)221 }222 private := func(s string) bool {223 return strings.Contains(s, ".ts.net") || slices.ContainsFunc(hosts, func(h string) bool { return strings.Contains(s, h) })224 }225 var out []Meta226 add := func(m Meta) {227 if m.Value != "" && !private(m.Value) {228 out = append(out, m)229 }230 }231 for _, l := range labelMeta {232 v := c.Config.Labels[l.label]233 m := Meta{Key: l.key, Value: v}234 switch l.key {235 case "Revision":236 if len(v) >= 7 {237 m.Value, m.Href = v[:min(len(v), 12)], r.CommitHref(v)238 }239 case "Source", "URL", "Documentation":240 if repo := b.giteaRepo(hosts, v); repo != "" {241 out = append(out, Meta{l.key, siteHost(b.Cfg.SiteURL) + "/" + repo, "/" + repo + "/"})242 continue243 }244 if u, err := url.Parse(v); err != nil || u.Scheme != "https" || u.Host == "" {245 continue246 }247 m.Href = v248 }249 add(m)250 }251 add(Meta{Key: "Entrypoint", Value: strings.Join(c.Config.Entrypoint, " ")})252 add(Meta{Key: "Command", Value: strings.Join(c.Config.Cmd, " ")})253 add(Meta{Key: "Ports", Value: strings.Join(slices.Sorted(maps.Keys(c.Config.ExposedPorts)), ", ")})254 add(Meta{Key: "User", Value: c.Config.User})255 return out256}257258// giteaRepo returns the allowlisted repo a URL on one of Gitea's hosts259// points at, or "".260func (b *Builder) giteaRepo(hosts []string, v string) string {261 u, err := url.Parse(v)262 if err != nil || !slices.Contains(hosts, u.Hostname()) {263 return ""264 }265 parts := strings.Split(strings.Trim(strings.TrimSuffix(u.Path, ".git"), "/"), "/")266 if len(parts) == 2 && parts[0] == b.Cfg.User && slices.Contains(b.Cfg.Repos, parts[1]) {267 return parts[1]268 }269 return ""270}