|
| 1 | +package database |
| 2 | + |
| 3 | +import ( |
| 4 | + "cmp" |
| 5 | + "database/sql" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "maps" |
| 9 | + "slices" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/jmoiron/sqlx" |
| 14 | +) |
| 15 | + |
| 16 | +const ( |
| 17 | + // imageWalkDepth is how many levels of references NewestImageDigests |
| 18 | + // follows below an image: nested indexes, a platform manifest, its blobs. |
| 19 | + imageWalkDepth = 4 |
| 20 | + // imageWalkBatch is how many digests one query looks up. |
| 21 | + imageWalkBatch = 500 |
| 22 | +) |
| 23 | + |
| 24 | +// ImageManifest is what one container image manifest of a repository |
| 25 | +// references. |
| 26 | +type ImageManifest struct { |
| 27 | + // PackagePURL is the repository as its blobs are cached. |
| 28 | + PackagePURL string |
| 29 | + Digest string |
| 30 | + // Refs are the digests of the manifests or blobs it references. |
| 31 | + Refs []string |
| 32 | + // TaggedAt is when a tag was last found to point at the manifest, or |
| 33 | + // zero for one only asked for by digest. |
| 34 | + TaggedAt time.Time |
| 35 | +} |
| 36 | + |
| 37 | +type imageManifestRow struct { |
| 38 | + Digest string `db:"digest"` |
| 39 | + Refs string `db:"refs"` |
| 40 | + TaggedAt int64 `db:"tagged_at"` |
| 41 | +} |
| 42 | + |
| 43 | +func (r imageManifestRow) refs() []string { |
| 44 | + return strings.Fields(r.Refs) |
| 45 | +} |
| 46 | + |
| 47 | +// RecordImageManifest stores a manifest's references. For one recorded |
| 48 | +// before it moves the tag time forward, and fills in the references if none |
| 49 | +// were known: a tag seen through a HEAD is recorded before its manifest is |
| 50 | +// read. |
| 51 | +func (db *DB) RecordImageManifest(m ImageManifest) error { |
| 52 | + tagged := int64(0) |
| 53 | + if !m.TaggedAt.IsZero() { |
| 54 | + tagged = m.TaggedAt.UnixMilli() |
| 55 | + } |
| 56 | + _, err := db.Exec(db.Rebind(` |
| 57 | + INSERT INTO image_manifests (package_purl, digest, refs, tagged_at, recorded_at) VALUES (?, ?, ?, ?, ?) |
| 58 | + ON CONFLICT (package_purl, digest) DO UPDATE SET |
| 59 | + tagged_at = CASE WHEN excluded.tagged_at > image_manifests.tagged_at THEN excluded.tagged_at ELSE image_manifests.tagged_at END, |
| 60 | + refs = CASE WHEN image_manifests.refs = '' THEN excluded.refs ELSE image_manifests.refs END |
| 61 | + WHERE image_manifests.tagged_at < excluded.tagged_at OR (image_manifests.refs = '' AND excluded.refs <> '') |
| 62 | + `), m.PackagePURL, m.Digest, strings.Join(m.Refs, "\n"), tagged, time.Now().UnixMilli()) |
| 63 | + return err |
| 64 | +} |
| 65 | + |
| 66 | +// ImageManifestState returns when a tag was last found to point at a |
| 67 | +// manifest, zero if none was, whether the manifest is recorded at all, and |
| 68 | +// whether its references are known. |
| 69 | +func (db *DB) ImageManifestState(packagePURL, digest string) (tagged time.Time, recorded, hasRefs bool, err error) { |
| 70 | + var row imageManifestRow |
| 71 | + err = db.Get(&row, db.Rebind(` |
| 72 | + SELECT digest, refs, tagged_at FROM image_manifests WHERE package_purl = ? AND digest = ? |
| 73 | + `), packagePURL, digest) |
| 74 | + if errors.Is(err, sql.ErrNoRows) { |
| 75 | + return time.Time{}, false, false, nil |
| 76 | + } |
| 77 | + if err != nil { |
| 78 | + return time.Time{}, false, false, err |
| 79 | + } |
| 80 | + if row.TaggedAt != 0 { |
| 81 | + tagged = time.UnixMilli(row.TaggedAt) |
| 82 | + } |
| 83 | + return tagged, true, row.Refs != "", nil |
| 84 | +} |
| 85 | + |
| 86 | +// NewestImageDigests returns the digests of the n images of a repository |
| 87 | +// that a tag was most recently found to point at, and of every manifest and |
| 88 | +// blob they reference. |
| 89 | +func (db *DB) NewestImageDigests(packagePURL string, n int) (map[string]struct{}, error) { |
| 90 | + digests, _, err := db.walkNewestImages(packagePURL, n) |
| 91 | + return digests, err |
| 92 | +} |
| 93 | + |
| 94 | +// ImageManifestRepositories returns the repositories that have recorded |
| 95 | +// manifests. |
| 96 | +func (db *DB) ImageManifestRepositories() ([]string, error) { |
| 97 | + var repositories []string |
| 98 | + err := db.Select(&repositories, `SELECT DISTINCT package_purl FROM image_manifests`) |
| 99 | + return repositories, err |
| 100 | +} |
| 101 | + |
| 102 | +// PruneImageManifests removes the manifests of a repository that its n |
| 103 | +// newest images do not reference and that were recorded before the given |
| 104 | +// time. The time leaves a manifest recorded shortly before the one that |
| 105 | +// references it in place. |
| 106 | +func (db *DB) PruneImageManifests(packagePURL string, n int, before time.Time) error { |
| 107 | + _, manifests, err := db.walkNewestImages(packagePURL, n) |
| 108 | + if err != nil { |
| 109 | + return err |
| 110 | + } |
| 111 | + query := `DELETE FROM image_manifests WHERE package_purl = ? AND recorded_at < ?` |
| 112 | + args := []any{packagePURL, before.UnixMilli()} |
| 113 | + if len(manifests) > 0 { |
| 114 | + query, args, err = sqlx.In(query+` AND digest NOT IN (?)`, packagePURL, before.UnixMilli(), manifests) |
| 115 | + if err != nil { |
| 116 | + return fmt.Errorf("building prune query: %w", err) |
| 117 | + } |
| 118 | + } |
| 119 | + _, err = db.Exec(db.Rebind(query), args...) |
| 120 | + return err |
| 121 | +} |
| 122 | + |
| 123 | +// walkNewestImages returns every digest the n newest images of a repository |
| 124 | +// reference, themselves included, and those among them that are recorded |
| 125 | +// manifests. |
| 126 | +func (db *DB) walkNewestImages(packagePURL string, n int) (map[string]struct{}, []string, error) { |
| 127 | + digests := map[string]struct{}{} |
| 128 | + if n <= 0 { |
| 129 | + return digests, nil, nil |
| 130 | + } |
| 131 | + rows, err := db.newestImages(packagePURL, n) |
| 132 | + if err != nil { |
| 133 | + return nil, nil, err |
| 134 | + } |
| 135 | + |
| 136 | + var manifests []string |
| 137 | + for _, row := range rows { |
| 138 | + digests[row.Digest] = struct{}{} |
| 139 | + } |
| 140 | + for depth := 0; len(rows) > 0; depth++ { |
| 141 | + var next []string |
| 142 | + for _, row := range rows { |
| 143 | + manifests = append(manifests, row.Digest) |
| 144 | + for _, ref := range row.refs() { |
| 145 | + if _, seen := digests[ref]; seen { |
| 146 | + continue |
| 147 | + } |
| 148 | + digests[ref] = struct{}{} |
| 149 | + next = append(next, ref) |
| 150 | + } |
| 151 | + } |
| 152 | + if depth == imageWalkDepth { |
| 153 | + break |
| 154 | + } |
| 155 | + if rows, err = db.imageManifestRows(packagePURL, next); err != nil { |
| 156 | + return nil, nil, err |
| 157 | + } |
| 158 | + } |
| 159 | + return digests, manifests, nil |
| 160 | +} |
| 161 | + |
| 162 | +// newestImages returns the n tagged manifests of a repository whose tag was |
| 163 | +// seen last. A registry serves a tag as an index to one client and as one |
| 164 | +// platform's manifest to a client that accepts no index, so a tagged |
| 165 | +// manifest that another tagged one references is that image seen another |
| 166 | +// way: it is no image of its own and lends the other its tag time. |
| 167 | +func (db *DB) newestImages(packagePURL string, n int) ([]imageManifestRow, error) { |
| 168 | + var rows []imageManifestRow |
| 169 | + err := db.Select(&rows, db.Rebind(` |
| 170 | + SELECT digest, refs, tagged_at FROM image_manifests |
| 171 | + WHERE package_purl = ? AND tagged_at > 0 |
| 172 | + `), packagePURL) |
| 173 | + if err != nil { |
| 174 | + return nil, err |
| 175 | + } |
| 176 | + |
| 177 | + tagged := make(map[string]int64, len(rows)) |
| 178 | + for _, row := range rows { |
| 179 | + tagged[row.Digest] = row.TaggedAt |
| 180 | + } |
| 181 | + seen := maps.Clone(tagged) |
| 182 | + referenced := map[string]struct{}{} |
| 183 | + for _, row := range rows { |
| 184 | + for _, ref := range row.refs() { |
| 185 | + at, ok := tagged[ref] |
| 186 | + if !ok || ref == row.Digest { |
| 187 | + continue |
| 188 | + } |
| 189 | + referenced[ref] = struct{}{} |
| 190 | + seen[row.Digest] = max(seen[row.Digest], at) |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + images := rows[:0:0] |
| 195 | + for _, row := range rows { |
| 196 | + if _, ok := referenced[row.Digest]; !ok { |
| 197 | + images = append(images, row) |
| 198 | + } |
| 199 | + } |
| 200 | + if len(images) == 0 { |
| 201 | + // Manifests that only reference each other; no registry serves these. |
| 202 | + images = rows |
| 203 | + } |
| 204 | + slices.SortFunc(images, func(a, b imageManifestRow) int { |
| 205 | + return cmp.Or( |
| 206 | + cmp.Compare(seen[b.Digest], seen[a.Digest]), |
| 207 | + cmp.Compare(b.TaggedAt, a.TaggedAt), |
| 208 | + cmp.Compare(a.Digest, b.Digest), |
| 209 | + ) |
| 210 | + }) |
| 211 | + return images[:min(n, len(images))], nil |
| 212 | +} |
| 213 | + |
| 214 | +// imageManifestRows returns the recorded manifests among digests. |
| 215 | +func (db *DB) imageManifestRows(packagePURL string, digests []string) ([]imageManifestRow, error) { |
| 216 | + var rows []imageManifestRow |
| 217 | + for start := 0; start < len(digests); start += imageWalkBatch { |
| 218 | + batch := digests[start:min(start+imageWalkBatch, len(digests))] |
| 219 | + query, args, err := sqlx.In(` |
| 220 | + SELECT digest, refs FROM image_manifests WHERE package_purl = ? AND digest IN (?) |
| 221 | + `, packagePURL, batch) |
| 222 | + if err != nil { |
| 223 | + return nil, fmt.Errorf("building image manifest query: %w", err) |
| 224 | + } |
| 225 | + var found []imageManifestRow |
| 226 | + if err := db.Select(&found, db.Rebind(query), args...); err != nil { |
| 227 | + return nil, err |
| 228 | + } |
| 229 | + rows = append(rows, found...) |
| 230 | + } |
| 231 | + return rows, nil |
| 232 | +} |
0 commit comments