Skip to content

Commit e1ab4a6

Browse files
authored
Merge pull request #702 from simonchrz/feat/retention-keep-latest-oci
Keep the blobs of the newest container images with keep_latest
2 parents 57428c5 + 7a867db commit e1ab4a6

21 files changed

Lines changed: 1298 additions & 24 deletions

‎config.example.yaml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,9 @@ storage:
118118
# How often to look for expired artifacts; at least "1m".
119119
sweep_interval: "10m"
120120
# Keep this many of the newest cached versions of each package from
121-
# eviction by age (cargo, golang, npm and pypi). 0 keeps none.
121+
# eviction by age (cargo, golang, npm and pypi). For oci it keeps the
122+
# blobs of this many images per repository, those a tag most recently
123+
# pointed at. 0 keeps none.
122124
# keep_latest: 2
123125

124126
# Store fetched artifacts. Set to false to stream every download from

‎docs/architecture.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,10 +205,21 @@ metadata_dates (
205205
last_modified INTEGER NOT NULL, -- Unix seconds; BIGINT on Postgres
206206
PRIMARY KEY (ecosystem, proxy_url, name)
207207
)
208+
209+
image_manifests (
210+
package_purl TEXT NOT NULL, -- the repository, as its blobs are cached
211+
digest TEXT NOT NULL,
212+
refs TEXT NOT NULL, -- digests it references, one per line
213+
tagged_at INTEGER NOT NULL, -- Unix ms a tag last pointed at it, 0 if none did; BIGINT on Postgres
214+
recorded_at INTEGER NOT NULL, -- Unix ms; BIGINT on Postgres
215+
PRIMARY KEY (package_purl, digest)
216+
)
208217
```
209218

210219
`metadata_dates` holds the `Last-Modified` served with rewritten metadata, such as npm packuments, Composer documents, PyPI simple pages and Helm indexes. A package's date is the second it started serving its current representation, and a new representation is only dated in a later second. Keeping it in the database means replicas sharing one serve the same date, and never give one representation's date to another, so `If-Modified-Since` cannot return 304 for a body the client does not have.
211220

221+
`image_manifests` is filled only with `storage.retention.keep_latest` set and a retention rule for `oci`. It holds which manifests and blobs each served container manifest references, so the retention sweep can keep the blobs of the newest images of a repository. The sweep also drops the rows of images that are no longer among the newest.
222+
212223
On PostgreSQL, `INTEGER PRIMARY KEY` becomes `SERIAL`, `DATETIME` becomes `TIMESTAMP`, `INTEGER DEFAULT 0` booleans become `BOOLEAN DEFAULT FALSE`, and size/count columns use `BIGINT`.
213224

214225
The `MigrateSchema()` function handles backward compatibility with older git-pkgs databases by running named migrations that add missing columns and tables. See [migrations.md](migrations.md) for how to add new schema changes.

‎docs/configuration.md‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ storage:
7171
| `storage.cache_artifacts` | `PROXY_STORAGE_CACHE_ARTIFACTS` | - | Store fetched artifacts (default: true); `false` streams them from upstream |
7272
| `storage.retention.default` | `PROXY_STORAGE_RETENTION_DEFAULT` | - | Evict artifacts not served for this long (e.g. "30d"); see [Retention](#retention) |
7373
| `storage.retention.sweep_interval` | `PROXY_STORAGE_RETENTION_SWEEP_INTERVAL` | - | How often expired artifacts are looked for (default: "10m", at least "1m") |
74-
| `storage.retention.keep_latest` | - | - | Keep this many of the newest cached versions of each package from eviction by age (default: 0); see [Retention](#retention) |
74+
| `storage.retention.keep_latest` | - | - | Keep this many of the newest cached versions of each package, or images of each repository, from eviction by age (default: 0); see [Retention](#retention) |
7575

7676
`storage.max_size` counts cached artifacts and cached metadata documents (`cache_metadata`). When the total goes over the limit, the least recently served entries of either kind are evicted first; an evicted metadata document is fetched from upstream again on the next request for it. Pushed artifacts are not counted or evicted. An artifact replaced by a refetch stays in storage for at least an hour, or `storage.direct_serve_ttl` if longer, so requests already reading it can finish, and storage use can exceed the limit by what was replaced in that time.
7777

@@ -127,7 +127,16 @@ storage:
127127
keep_latest: 2
128128
```
129129

130-
With this, the files of the two highest cached versions of a package are never evicted by age, and older versions expire by their rule as before. Versions are ordered by the ecosystem's version rules, not by when they were fetched, and a prerelease counts like any other version. Only versions in the cache count, not those upstream, so the kept ones need not be the latest releases. `keep_latest` applies to `cargo`, `golang`, `npm` and `pypi`; the other ecosystems ignore it, since many of them cache files under a digest or a build rather than a version. On startup the proxy logs the ecosystems it reaches (`keep_latest_covered`). `storage.max_size` can still evict a kept version.
130+
With this, the files of the two highest cached versions of a package are never evicted by age, and older versions expire by their rule as before. Versions are ordered by the ecosystem's version rules, not by when they were fetched, and a prerelease counts like any other version. Only versions in the cache count, not those upstream, so the kept ones need not be the latest releases. `keep_latest` applies to `cargo`, `golang`, `npm`, `pypi` and, by image, `oci`; the other ecosystems ignore it, since many of them cache files under a digest or a build rather than a version. On startup the proxy logs the ecosystems it reaches (`keep_latest_covered`). `storage.max_size` can still evict a kept version.
131+
132+
For `oci` there are no versions to order, so `keep_latest` counts images instead: it keeps the blobs of the images of a repository that a tag most recently pointed at. With `keep_latest: 2` and one tag such as `beta` in use, that is the image `beta` points at now and the one it pointed at before. The count is per repository, not per tag, so with several tags in use set it at least that high. A blob that a kept image shares with an older one stays.
133+
134+
To know which blobs an image needs, the proxy records what each manifest it serves references, in the `image_manifests` table, while `keep_latest` is set and a retention rule applies to `oci`. This has a few consequences:
135+
136+
- An image only counts once its tag was pulled or mirrored with `keep_latest` set, and its blobs are known once its platform manifest was pulled too. Until then they expire by their rule as before.
137+
- An image pulled only by digest is not counted and not kept.
138+
- A multi-platform tag counts as one image, also when a client that accepts no image index was served one platform's manifest for it.
139+
- Homebrew bottles and Helm charts pulled over OCI are images here: the newest versions of a bottle or chart are those whose tags were last asked for.
131140

132141
Generic retention is opt-in because release assets may disappear upstream and cannot then be downloaded again after eviction. An existing `default` never starts evicting generic downloads. Set `ecosystems.generic: "30d"` to cover all generic artifacts, or configure only selected GitHub repositories:
133142

‎internal/database/database_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -613,7 +613,7 @@ func createTestPostgresDB(t *testing.T) *DB {
613613
// Drop and recreate every table CreateSchema creates for clean test state;
614614
// leftover migration records make the next CreateSchema fail on the
615615
// migrations primary key.
616-
tables := []string{"artifacts", "pending_deletes", "versions", "packages", "vulnerabilities", "metadata_cache", "metadata_dates", "job_runs", "fetch_leases", "upstream_holds", "metadata_snapshots", "projects", "project_components", "migrations", "schema_info"}
616+
tables := []string{"artifacts", "pending_deletes", "versions", "packages", "vulnerabilities", "metadata_cache", "metadata_dates", "image_manifests", "job_runs", "fetch_leases", "upstream_holds", "metadata_snapshots", "projects", "project_components", "migrations", "schema_info"}
617617
for _, table := range tables {
618618
_, _ = db.Exec("DROP TABLE IF EXISTS " + table + " CASCADE")
619619
}
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
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

Comments
 (0)