From d21aeaf0f61c9ce7d2986256b849cf1a6a591ae2 Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:04:44 +0100 Subject: [PATCH 1/8] docs(agent): describe the registry mirror The image cache could only pull a reference that names the registry address. This describes one global mirror, tried before the registry the source names, as containerd does, so the ImageCache sources keep the real image name. The next commits implement it. Refs: MK8S-553 --- agent/DESIGN.md | 44 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/agent/DESIGN.md b/agent/DESIGN.md index fd5d0b8..a3bd0c7 100644 --- a/agent/DESIGN.md +++ b/agent/DESIGN.md @@ -337,7 +337,43 @@ Pulling and extraction use goes with `--ca-file`, which covers the registries that serve TLS, and excludes `--insecure-skip-tls-verify`, meant for test clusters only. `imagecachectl import` keeps a `--plain-http` switch: it pulls one source - per run, so the switch already covers that source's registry alone. + per run, so the switch already covers that source's registry alone, or + the mirror when `--mirror` is given. +- The library has no mirror support. `--mirror ` adds one global + mirror, tried before the registry each source names, as containerd does with + `hosts.toml`. The source keeps its real name (`ghcr.io/scality/...`), and + the puller builds `/:` (or `@`) from the + mirror's registry name, never by parsing a string: a short host name would + read as a Docker Hub repository. Each registry API request to the mirror, + under `/v2/`, carries `ns=`, the query parameter containerd sends; + a registry that honours it prepends it to the repository. Docker Hub goes as + `ns=docker.io`. The mirror is a registry like any other: `--ca-file` covers + it, and it is reached over plain HTTP only if `--plain-http-registry` lists + it. Rewriting the reference rather than the host of each request lets the + library pick the scheme and name the mirror in its errors. + The choice is made before any layer streams. A pull uses the mirror once it + has resolved the manifest and the configuration and answered a HEAD for + every layer: without the HEAD, a mirror missing one layer would fail the + pull on every pass and the registry would never be tried. A resolve (the + adoption check) reads no layer, so it asks no HEAD. Otherwise the registry + is tried, and when both fail the error carries both causes. When the + registry answers, the mirror's failure is logged rather than returned, since + nothing failed: the agent logs it, and `imagecachectl` prints it as a + warning. The layers then stream from whichever answered: a mirror lost + during the stream fails the pull, and the next pass resolves again. + The mirror is trusted the way containerd trusts one. It is expected to hold + the images: a pull-through proxy that fetches a blob only on a GET would + answer the HEAD with a 404 and be passed over. For a source by tag, the + mirror's tag wins, even if the registry has moved it since; a source by + digest does not have that gap. The sentinel records the source as the + resource gives it, never the mirror reference. A source that already names + the mirror is pulled once, with no `ns`. One mirror per registry is out of + scope. + `imagecachectl import --mirror` does the same. Its `--plain-http` then goes + to the mirror, not to the source's registry, so it goes with `--ca-file`, + which covers that registry. The command runs on a host that may resolve no + cluster name, so the mirror is given in a form the host can reach, such as + an IP. The cache images are regular container images (they must remain importable and mountable with `ctr` by provisioning tooling), so an artifact-oriented @@ -471,7 +507,9 @@ The agent never writes ImageCache resources (no status, no finalizers). nobody listens on leaves the node `pending`. Two registries run in the cluster: a pull over plain HTTP lands on the selected node only, and a registry signed by a private CA is refused until the shipped CA patch is - applied. An archive rewritten on the node with other content of the same - size is extracted again. `imagecachectl` seeds two directories on the + applied. With `--mirror`, a source the registry does not hold is pulled + from the mirror, then from the registry once the mirror is stopped. An + archive rewritten on the node with other content of the same size is + extracted again. `imagecachectl` seeds two directories on the worker: the agent adopts the one holding the image its resource names, with no extraction, and replaces the other. From b33d7d4901452ba2c03520c4fa37340aa1faa449 Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:05:00 +0100 Subject: [PATCH 2/8] refactor(puller): build the registries of a Remote in one place Both ways to build a Remote checked the plain HTTP list on their own. The mirror adds a second registry to check, so the two now share withRegistries. No change in behaviour. Refs: MK8S-553 --- agent/internal/puller/puller.go | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index 5ae8d73..a9eb89a 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -91,11 +91,7 @@ type TLS struct { func NewRemote(cfg TLS) (Remote, error) { // Without a certificate setting, the library default transport does. if cfg.CAFile == "" && !cfg.SkipVerify { - plain, err := plainHTTPRegistries(cfg.PlainHTTPRegistries) - if err != nil { - return Remote{}, err - } - return Remote{plainHTTP: plain}, nil + return withRegistries(Remote{}, cfg) } // The library declares its default as an *http.Transport. return newRemote(cfg, remote.DefaultTransport.(*http.Transport)) @@ -112,10 +108,6 @@ func newRemote(cfg TLS, base *http.Transport) (Remote, error) { return Remote{}, errors.Wrap(ErrTLS, errors.WithDetail("plain HTTP registries are not meant for a test cluster that verifies no certificate")) } - plain, err := plainHTTPRegistries(cfg.PlainHTTPRegistries) - if err != nil { - return Remote{}, err - } t := base.Clone() switch { case cfg.SkipVerify: @@ -127,7 +119,18 @@ func newRemote(cfg TLS, base *http.Transport) (Remote, error) { } t.TLSClientConfig = &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12} } - return Remote{transport: t, plainHTTP: plain}, nil + return withRegistries(Remote{transport: t}, cfg) +} + +// withRegistries checks and normalizes the registries cfg names, and sets +// them on r. +func withRegistries(r Remote, cfg TLS) (Remote, error) { + plain, err := plainHTTPRegistries(cfg.PlainHTTPRegistries) + if err != nil { + return Remote{}, err + } + r.plainHTTP = plain + return r, nil } // plainHTTPRegistries checks each entry is a host[:port] and normalizes it the From e0f1ec3c9ada0f32b193935da22eafb865a9f4cf Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:06:30 +0100 Subject: [PATCH 3/8] feat(puller): pull through a registry mirror, then the source registry With a mirror, a source keeps its real name, like ghcr.io/scality/x:1.0, and is pulled from /scality/x:1.0 first, with ns=ghcr.io on the registry API requests, as containerd does. When the mirror fails, the registry the source names is tried, and when both fail the error carries both causes. The mirror reference is built from the mirror registry, so a short host name stays the registry, and the mirror goes through the same TLS and plain HTTP settings as any registry. Refs: MK8S-553 --- agent/internal/puller/puller.go | 125 +++++++++- agent/internal/puller/puller_test.go | 339 +++++++++++++++++++++++++++ 2 files changed, 462 insertions(+), 2 deletions(-) diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index a9eb89a..4a9d2b2 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -5,11 +5,14 @@ import ( "context" "crypto/tls" "crypto/x509" + stderrors "errors" "fmt" "io" "net/http" + "net/url" "os" "slices" + "strings" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" @@ -38,6 +41,8 @@ var ( // ErrUnlistedPlainHTTP covers a plain HTTP request to a registry that is // not listed, refused before it leaves, see httpsOnly. ErrUnlistedPlainHTTP = errors.New("plain HTTP to an unlisted registry refused") + // ErrMirror covers a mirror that is not a host[:port]. + ErrMirror = errors.New("invalid registry mirror") ) // Image identifies what a source resolved to. @@ -72,6 +77,8 @@ type Remote struct { // plainHTTP lists the registries marked insecure, normalized as // name.Registry.RegistryStr returns them, see TLS.PlainHTTPRegistries. plainHTTP []string + // mirror is TLS.Mirror, marked insecure when plainHTTP lists it, or nil. + mirror *name.Registry } // TLS says how a Remote reaches the registry and checks its certificate. @@ -84,6 +91,11 @@ type TLS struct { // PlainHTTPRegistries lists the registries, as host[:port], the pull may // reach over plain HTTP, see agent/README.md for the matching rules. PlainHTTPRegistries []string + // Mirror is a registry, as host[:port], tried before the registry each + // reference names, see "Image pulling" in agent/DESIGN.md. The settings + // above apply to it like to any registry: it is reached over plain HTTP + // only if it is listed in PlainHTTPRegistries. + Mirror string } // NewRemote returns a Remote that reaches the registry as cfg says. The CA @@ -125,11 +137,34 @@ func newRemote(cfg TLS, base *http.Transport) (Remote, error) { // withRegistries checks and normalizes the registries cfg names, and sets // them on r. func withRegistries(r Remote, cfg TLS) (Remote, error) { + // The mirror first: imagecachectl copies it into the plain HTTP list, + // and a bad one is better named as the mirror. + var mirror name.Registry + if cfg.Mirror != "" { + var err error + mirror, err = name.NewRegistry(cfg.Mirror, name.StrictValidation) + if err != nil { + return Remote{}, errors.Wrap(ErrMirror, errors.CausedBy(err), + errors.WithDetail("want host[:port], with no scheme and no path"), + errors.WithProperty("mirror", cfg.Mirror)) + } + } plain, err := plainHTTPRegistries(cfg.PlainHTTPRegistries) if err != nil { return Remote{}, err } r.plainHTTP = plain + if cfg.Mirror != "" { + // Insecure is an option of the parse, so a listed mirror is parsed + // again with it. + if slices.Contains(plain, mirror.RegistryStr()) { + if mirror, err = name.NewRegistry(cfg.Mirror, name.StrictValidation, name.Insecure); err != nil { + return Remote{}, errors.Wrap(ErrMirror, errors.CausedBy(err), + errors.WithProperty("mirror", cfg.Mirror)) + } + } + r.mirror = &mirror + } return r, nil } @@ -198,7 +233,48 @@ func (r Remote) Resolve(ctx context.Context, ref string) (Image, error) { // open resolves ref to its linux/amd64 image. It reads the manifest and the // configuration, never a layer: those are fetched as the stream is read. +// +// With a mirror, the mirror is tried first and the registry ref names next. +// See "Image pulling" in agent/DESIGN.md. func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { + parsed, err := r.parse(ref) + if err != nil { + return nil, Image{}, err + } + upstream := parsed.Context().RegistryStr() + if r.mirror == nil || r.mirror.RegistryStr() == upstream { + return r.openFrom(ctx, parsed, ref, "") + } + onMirror := r.onMirror(parsed) + img, id, mirrorErr := r.openFrom(ctx, onMirror, onMirror.String(), namespace(upstream)) + // A cancelled pull would fail the same way on the registry. + if mirrorErr == nil || ctx.Err() != nil { + return img, id, mirrorErr + } + img, id, err = r.openFrom(ctx, parsed, ref, "") + if err != nil { + return nil, Image{}, errors.Wrap(ErrPull, errors.CausedBy(stderrors.Join(mirrorErr, err)), + errors.WithDetail("neither the mirror nor the registry served the image"), + errors.WithProperty("source", ref), errors.WithProperty("mirror", r.mirror.RegistryStr())) + } + return img, id, nil +} + +// onMirror returns parsed with its registry replaced by the mirror. It is +// built from the registry rather than parsed from a string: a mirror named +// with no dot and no port, such as a short host name, would read as the +// first path element of a Docker Hub repository. +func (r Remote) onMirror(parsed name.Reference) name.Reference { + repo := r.mirror.Repo(parsed.Context().RepositoryStr()) + if _, ok := parsed.(name.Digest); ok { + return repo.Digest(parsed.Identifier()) + } + return repo.Tag(parsed.Identifier()) +} + +// parse parses ref, marked insecure when its registry is listed for plain +// HTTP. +func (r Remote) parse(ref string) (name.Reference, error) { parsed, err := name.ParseReference(ref) if err == nil && slices.Contains(r.plainHTTP, parsed.Context().RegistryStr()) { // The library then races HTTPS and HTTP for this registry alone, @@ -206,19 +282,29 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { parsed, err = name.ParseReference(ref, name.Insecure) } if err != nil { - return nil, Image{}, errors.Wrap(ErrReference, errors.CausedBy(err), + return nil, errors.Wrap(ErrReference, errors.CausedBy(err), errors.WithProperty("source", ref)) } + return parsed, nil +} + +// openFrom resolves parsed. A non-empty ns is sent to the mirror, see +// withNamespace. +func (r Remote) openFrom(ctx context.Context, parsed name.Reference, ref, ns string) (v1.Image, Image, error) { // Read at each pull rather than once, so the library default stays the // one in force, as it would be without a transport of ours. next := r.transport if next == nil { next = remote.DefaultTransport } + var t http.RoundTripper = httpsOnly{next: next, plain: r.plainHTTP, registry: parsed.Context().RegistryStr()} + if ns != "" { + t = withNamespace{next: t, host: r.mirror.RegistryStr(), ns: ns} + } opts := []remote.Option{ remote.WithContext(ctx), remote.WithPlatform(platform), - remote.WithTransport(httpsOnly{next: next, plain: r.plainHTTP, registry: parsed.Context().RegistryStr()}), + remote.WithTransport(t), } img, err := remote.Image(parsed, opts...) if err != nil { @@ -229,6 +315,41 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { return img, id, err } +// namespace is the ns a mirror receives for a registry. Docker Hub goes by +// docker.io there, as containerd sends it, not by the host the library uses. +func namespace(registry string) string { + if registry == name.DefaultRegistry { + return "docker.io" + } + return registry +} + +// withNamespace adds the ns query parameter to the registry API requests sent +// to the mirror, under /v2/. It names the registry the image comes from, the +// way containerd passes it to a mirror. Any other request, such as one to a +// token server or a signed URL the mirror redirects to, goes out unchanged. +type withNamespace struct { + next http.RoundTripper + host, ns string +} + +// RoundTrip implements http.RoundTripper. +func (t withNamespace) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Host != t.host || !strings.HasPrefix(req.URL.Path, "/v2/") { + return t.next.RoundTrip(req) + } + // A RoundTripper must not change the request it is given. The query is + // appended to rather than encoded again, which would reorder it. + req = req.Clone(req.Context()) + ns := "ns=" + url.QueryEscape(t.ns) + if req.URL.RawQuery == "" { + req.URL.RawQuery = ns + } else { + req.URL.RawQuery += "&" + ns + } + return t.next.RoundTrip(req) +} + // httpsOnly refuses a plain HTTP request to the pulled registry unless it is // listed. The library also races HTTP for a private or loopback IP and for a // localhost name, whatever the list says, see "Pulling and extraction" in diff --git a/agent/internal/puller/puller_test.go b/agent/internal/puller/puller_test.go index 87826f7..229f8fc 100644 --- a/agent/internal/puller/puller_test.go +++ b/agent/internal/puller/puller_test.go @@ -1571,3 +1571,342 @@ func TestNewRemoteRefusesPlainHTTPRegistriesWithSkipVerify(t *testing.T) { t.Fatalf("err = %v, want ErrTLS", err) } } + +// mirrored returns a Remote built the way NewRemote builds it, with mirror and +// the plain HTTP registries given, that reaches the registries through rt. +func mirrored(t *testing.T, rt http.RoundTripper, mirror string, plain ...string) Remote { + t.Helper() + r, err := withRegistries(Remote{transport: rt}, TLS{Mirror: mirror, PlainHTTPRegistries: plain}) + if err != nil { + t.Fatal(err) + } + return r +} + +// mirrorTest is a plain HTTP registry that records the ns parameter of every +// request it receives. +type mirrorTest struct { + host string + srv *httptest.Server + mu sync.Mutex + ns []string + // onRequest, when set, runs on each request before it is served. + onRequest func() +} + +// newMirrorTest serves an empty in-memory registry. Its host is +// example.com:, reached through loopbackTransport. +func newMirrorTest(t *testing.T) *mirrorTest { + t.Helper() + m := &mirrorTest{} + reg := registry.New() + m.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + m.mu.Lock() + m.ns = append(m.ns, r.URL.Query().Get("ns")) + hook := m.onRequest + m.mu.Unlock() + if hook != nil { + hook() + } + reg.ServeHTTP(w, r) + })) + t.Cleanup(m.srv.Close) + _, port, _ := net.SplitHostPort(strings.TrimPrefix(m.srv.URL, "http://")) + m.host = "example.com:" + port + return m +} + +// push stores img under path, and returns its digest. The push goes to the +// loopback address, and its requests are not recorded. +func (m *mirrorTest) push(t *testing.T, path string, img v1.Image) string { + t.Helper() + m.mu.Lock() + before := len(m.ns) + m.mu.Unlock() + if err := crane.Push(img, strings.TrimPrefix(m.srv.URL, "http://")+path); err != nil { + t.Fatal(err) + } + m.mu.Lock() + m.ns = m.ns[:before] + m.mu.Unlock() + d, err := img.Digest() + if err != nil { + t.Fatal(err) + } + return d.String() +} + +func (m *mirrorTest) seen() []string { + m.mu.Lock() + defer m.mu.Unlock() + return slices.Clone(m.ns) +} + +func workerImage(t *testing.T) v1.Image { + t.Helper() + img, err := crane.Image(map[string][]byte{etcdTarPath: []byte(etcdBody)}) + if err != nil { + t.Fatal(err) + } + return img +} + +// pullAll pulls ref and reads the whole stream, the layers included. +func pullAll(r Remote, ref string) (Image, error) { + rc, id, err := r.Pull(context.Background(), ref) + if err != nil { + return Image{}, err + } + _, err = io.Copy(io.Discard, rc) + if cerr := rc.Close(); err == nil { + err = cerr + } + return id, err +} + +// The mirror serves the image and the registry is never asked. Each request +// to the mirror carries the ns of the source's registry: Docker Hub goes as +// docker.io, as containerd sends it, and a source that already names the +// mirror carries none. +func TestRemotePullTriesTheMirrorFirst(t *testing.T) { + const dockerHub = "docker.io" + for _, tc := range []struct { + name, path string + source func(upstream, mirror, digest string) string + ns func(upstream string) string + }{ + {"tag", workerRefPath, + func(up, _, _ string) string { return up + workerRefPath }, + func(up string) string { return up }}, + {"digest", workerRefPath, + func(up, _, d string) string { return up + "/boot-cache/worker@" + d }, + func(up string) string { return up }}, + {"docker hub", "/library/worker:1.0.0", + func(_, _, _ string) string { return "worker:1.0.0" }, + func(string) string { return dockerHub }}, + {"source on the mirror", workerRefPath, + func(_, m, _ string) string { return m + workerRefPath }, + func(string) string { return "" }}, + } { + t.Run(tc.name, func(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + digest := mirror.push(t, tc.path, workerImage(t)) + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + id, err := pullAll(r, tc.source(upstream.host, mirror.host, digest)) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + seen := mirror.seen() + if len(seen) == 0 { + t.Fatal("the mirror received no request") + } + for _, ns := range seen { + if want := tc.ns(upstream.host); ns != want { + t.Errorf("the mirror received ns=%q, want %q", ns, want) + } + } + if n := len(upstream.seen()); n != 0 { + t.Errorf("the registry received %d requests, want none", n) + } + }) + } +} + +func TestRemotePullFallsBackOnTheRegistry(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + digest := upstream.push(t, workerRefPath, workerImage(t)) + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + id, err := pullAll(r, upstream.host+workerRefPath) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + if len(mirror.seen()) == 0 { + t.Error("the mirror was not tried first") + } + for _, ns := range upstream.seen() { + if ns != "" { + t.Errorf("the registry received ns=%q, want none", ns) + } + } +} + +func TestRemotePullNamesBothFailures(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + mirror.srv.Close() + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + _, err := pullAll(r, upstream.host+workerRefPath) + if !errors.Is(err, ErrPull) { + t.Fatalf("err = %v, want ErrPull", err) + } + for _, want := range []string{"connection refused", "NAME_UNKNOWN"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("err = %v, want it to carry %q", err, want) + } + } +} + +// The mirror follows the plain HTTP list like any registry: unlisted, it is +// reached over HTTPS only, which a plain HTTP server cannot answer. +func TestRemotePullReachesAnUnlistedMirrorOverHTTPSOnly(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + mirror.push(t, workerRefPath, workerImage(t)) + digest := upstream.push(t, workerRefPath, workerImage(t)) + r := mirrored(t, loopbackTransport("", t), mirror.host, upstream.host) + + id, err := pullAll(r, upstream.host+workerRefPath) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + if n := len(mirror.seen()); n != 0 { + t.Errorf("the mirror received %d plain HTTP requests, want none", n) + } +} + +// --ca-file covers the mirror. tlsRegistry dials its server for any host, +// and its certificate covers example.com only: a pull that reached the +// registry instead of the mirror would fail on the name. +func TestRemotePullTrustsTheGivenCAForTheMirror(t *testing.T) { + ref, caFile, base := tlsRegistry(t) + r, err := newRemote(TLS{CAFile: caFile, Mirror: registryOf(t, ref)}, base) + if err != nil { + t.Fatal(err) + } + + if _, err := pullAll(r, "registry.local:5000"+workerRefPath); err != nil { + t.Fatal(err) + } +} + +func TestNewRemoteRejectsAMirrorThatIsNotAHost(t *testing.T) { + for _, m := range []string{"https://registry.local", "registry.local/path", "Registry.local:x"} { + if _, err := NewRemote(TLS{Mirror: m}); !errors.Is(err, ErrMirror) { + t.Errorf("NewRemote(Mirror: %q) err = %v, want ErrMirror", m, err) + } + } +} + +// counting counts the requests to host that reach the transport, sent or not: +// a cancelled context stops a request before the server sees it. +type counting struct { + next http.RoundTripper + host string + n atomic.Int32 +} + +func (c *counting) RoundTrip(req *http.Request) (*http.Response, error) { + if req.URL.Host == c.host { + c.n.Add(1) + } + return c.next.RoundTrip(req) +} + +// A pull cancelled while the mirror is tried stops there: the registry is not +// even attempted. +func TestRemotePullCancelledOnTheMirrorSkipsTheRegistry(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + upstream.push(t, workerRefPath, workerImage(t)) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + mirror.mu.Lock() + mirror.onRequest = cancel + mirror.mu.Unlock() + toUpstream := &counting{next: loopbackTransport("", t), host: upstream.host} + r := mirrored(t, toUpstream, mirror.host, mirror.host, upstream.host) + + _, err := r.Resolve(ctx, upstream.host+workerRefPath) + if !errors.Is(err, context.Canceled) { + t.Fatalf("err = %v, want context.Canceled", err) + } + if n := toUpstream.n.Load(); n != 0 { + t.Errorf("%d requests to the registry after the cancel, want none", n) + } +} + +// The mirror reference keeps the mirror as its registry whatever the shape of +// its name. Parsed back from a string, a short host name would read as a +// Docker Hub repository. +func TestOnMirrorKeepsTheMirrorAsRegistry(t *testing.T) { + const source, short, ip = "ghcr.io/scality/x:1.0", "mirror", "10.0.0.1:5000" + for _, tc := range []struct{ mirror, source, want string }{ + {short, source, "mirror/scality/x:1.0"}, + {"localhost", source, "localhost/scality/x:1.0"}, + {ip, source, ip + "/scality/x:1.0"}, + {short, "ghcr.io/scality/x@sha256:" + strings.Repeat("a", 64), + "mirror/scality/x@sha256:" + strings.Repeat("a", 64)}, + {short, "x:1.0", "mirror/library/x:1.0"}, + } { + t.Run(tc.mirror+" "+tc.source, func(t *testing.T) { + parsed, err := name.ParseReference(tc.source) + if err != nil { + t.Fatal(err) + } + got := mirrored(t, nil, tc.mirror).onMirror(parsed) + if got.Context().RegistryStr() != tc.mirror { + t.Errorf("registry = %q, want %q", got.Context().RegistryStr(), tc.mirror) + } + if got.String() != tc.want { + t.Errorf("reference = %q, want %q", got.String(), tc.want) + } + }) + } +} + +// A mirror listed for plain HTTP keeps that mark on its reference. +func TestOnMirrorMarksAListedMirrorInsecure(t *testing.T) { + parsed, err := name.ParseReference("ghcr.io/scality/y:1.0") + if err != nil { + t.Fatal(err) + } + const short = "mirror" + got := mirrored(t, nil, short, short).onMirror(parsed) + if scheme := got.Context().Scheme(); scheme != "http" { + t.Errorf("scheme = %q, want http", scheme) + } +} + +// roundTripFunc records the request it is given. +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } + +// ns goes on the registry API requests to the mirror only, appended to the +// query they carry, and the request given is left as it was. +func TestWithNamespaceTouchesOnlyRegistryCallsToTheMirror(t *testing.T) { + for _, tc := range []struct{ url, want string }{ + {"https://mirror/v2/scality/x/manifests/1", "ns=ghcr.io"}, + {"https://mirror/v2/scality/x/blobs/sha256:a?digest=b", "digest=b&ns=ghcr.io"}, + {"https://mirror/token?scope=pull", "scope=pull"}, + {"https://storage/v2/scality/x/blobs/sha256:a?X-Amz-Signature=s", "X-Amz-Signature=s"}, + } { + t.Run(tc.url, func(t *testing.T) { + var got string + rt := withNamespace{host: "mirror", ns: "ghcr.io", next: roundTripFunc(func(r *http.Request) (*http.Response, error) { + got = r.URL.RawQuery + return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody}, nil + })} + req := httptest.NewRequest(http.MethodGet, tc.url, nil) + before := req.URL.RawQuery + if _, err := rt.RoundTrip(req); err != nil { + t.Fatal(err) + } + if got != tc.want { + t.Errorf("query = %q, want %q", got, tc.want) + } + if req.URL.RawQuery != before { + t.Errorf("the request given was changed: %q", req.URL.RawQuery) + } + }) + } +} From 9444fad1e3929798bc35198eaba4c654356b20f9 Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:07:17 +0100 Subject: [PATCH 4/8] feat(puller): use the mirror for a pull only when it holds every layer The layers stream after the mirror is picked. A mirror that served the manifest but missed a layer then failed the pull on every pass, and the registry was never tried. A pull now sends a HEAD for each layer before it picks the mirror. The adoption check reads no layer, so it does not. Refs: MK8S-553 --- agent/internal/puller/puller.go | 40 +++++++- agent/internal/puller/puller_test.go | 132 ++++++++++++++++++++++++++- 2 files changed, 165 insertions(+), 7 deletions(-) diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index 4a9d2b2..155a0b9 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -16,6 +16,7 @@ import ( "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/partial" "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/google/go-containerregistry/pkg/v1/tarball" "github.com/scality/go-errors" @@ -218,7 +219,7 @@ var platform = v1.Platform{OS: "linux", Architecture: "amd64"} // Pull implements Puller. func (r Remote) Pull(ctx context.Context, ref string) (io.ReadCloser, Image, error) { - img, id, err := r.open(ctx, ref) + img, id, err := r.open(ctx, ref, true) if err != nil { return nil, Image{}, err } @@ -227,7 +228,7 @@ func (r Remote) Pull(ctx context.Context, ref string) (io.ReadCloser, Image, err // Resolve implements Puller. func (r Remote) Resolve(ctx context.Context, ref string) (Image, error) { - _, id, err := r.open(ctx, ref) + _, id, err := r.open(ctx, ref, false) return id, err } @@ -235,8 +236,9 @@ func (r Remote) Resolve(ctx context.Context, ref string) (Image, error) { // configuration, never a layer: those are fetched as the stream is read. // // With a mirror, the mirror is tried first and the registry ref names next. -// See "Image pulling" in agent/DESIGN.md. -func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { +// For a pull, the mirror must also answer a HEAD for each layer: a resolve +// reads no layer, so it does not ask. See "Image pulling" in agent/DESIGN.md. +func (r Remote) open(ctx context.Context, ref string, layers bool) (v1.Image, Image, error) { parsed, err := r.parse(ref) if err != nil { return nil, Image{}, err @@ -247,6 +249,9 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { } onMirror := r.onMirror(parsed) img, id, mirrorErr := r.openFrom(ctx, onMirror, onMirror.String(), namespace(upstream)) + if mirrorErr == nil && layers { + mirrorErr = holdsLayers(img, onMirror.String()) + } // A cancelled pull would fail the same way on the registry. if mirrorErr == nil || ctx.Err() != nil { return img, id, mirrorErr @@ -260,6 +265,33 @@ func (r Remote) open(ctx context.Context, ref string) (v1.Image, Image, error) { return img, id, nil } +// holdsLayers checks that the mirror has every layer of img, with one HEAD +// request per layer. +func holdsLayers(img v1.Image, ref string) error { + layers, err := img.Layers() + if err != nil { + return errors.Wrap(ErrPull, errors.CausedBy(err), + errors.WithDetail("listing the layers"), errors.WithProperty("source", ref)) + } + for _, l := range layers { + ok, err := partial.Exists(l) + if err == nil && ok { + continue + } + opts := []errors.Option{errors.WithDetail("the mirror misses a layer"), errors.WithProperty("source", ref)} + if d, derr := l.Digest(); derr == nil { + opts = append(opts, errors.WithProperty("layer", d.String())) + } + // A 404 comes back as false with no error, and an empty cause + // would make the message panic. + if err != nil { + opts = append(opts, errors.CausedBy(err)) + } + return errors.Wrap(ErrPull, opts...) + } + return nil +} + // onMirror returns parsed with its registry replaced by the mirror. It is // built from the registry rather than parsed from a string: a mirror named // with no dot and no port, such as a short host name, would read as the diff --git a/agent/internal/puller/puller_test.go b/agent/internal/puller/puller_test.go index 229f8fc..ec564b9 100644 --- a/agent/internal/puller/puller_test.go +++ b/agent/internal/puller/puller_test.go @@ -1590,6 +1590,12 @@ type mirrorTest struct { srv *httptest.Server mu sync.Mutex ns []string + // broken is a blob digest answered with brokenStatus, as a registry + // that lost it or fails on it would. + broken string + brokenStatus int + // heads lists the paths of the HEAD requests received. + heads []string // onRequest, when set, runs on each request before it is served. onRequest func() } @@ -1603,11 +1609,18 @@ func newMirrorTest(t *testing.T) *mirrorTest { m.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { m.mu.Lock() m.ns = append(m.ns, r.URL.Query().Get("ns")) - hook := m.onRequest + if r.Method == http.MethodHead { + m.heads = append(m.heads, r.URL.Path) + } + broken, status, hook := m.broken, m.brokenStatus, m.onRequest m.mu.Unlock() if hook != nil { hook() } + if broken != "" && strings.HasSuffix(r.URL.Path, "/blobs/"+broken) { + w.WriteHeader(status) + return + } reg.ServeHTTP(w, r) })) t.Cleanup(m.srv.Close) @@ -1621,13 +1634,13 @@ func newMirrorTest(t *testing.T) *mirrorTest { func (m *mirrorTest) push(t *testing.T, path string, img v1.Image) string { t.Helper() m.mu.Lock() - before := len(m.ns) + before, beforeHeads := len(m.ns), len(m.heads) m.mu.Unlock() if err := crane.Push(img, strings.TrimPrefix(m.srv.URL, "http://")+path); err != nil { t.Fatal(err) } m.mu.Lock() - m.ns = m.ns[:before] + m.ns, m.heads = m.ns[:before], m.heads[:beforeHeads] m.mu.Unlock() d, err := img.Digest() if err != nil { @@ -1797,6 +1810,95 @@ func TestNewRemoteRejectsAMirrorThatIsNotAHost(t *testing.T) { } } +// breakLayer makes the mirror answer status for the only layer of img. +func (m *mirrorTest) breakLayer(t *testing.T, img v1.Image, status int) string { + t.Helper() + layers, err := img.Layers() + if err != nil || len(layers) != 1 { + t.Fatalf("want one layer, got %d (%v)", len(layers), err) + } + d, err := layers[0].Digest() + if err != nil { + t.Fatal(err) + } + m.mu.Lock() + m.broken, m.brokenStatus = d.String(), status + m.mu.Unlock() + return d.String() +} + +// A mirror that holds the manifest and the configuration but misses a layer +// is passed over before the layers stream, for a 404 as for a server error. +func TestRemotePullFallsBackWhenTheMirrorMissesALayer(t *testing.T) { + for _, status := range []int{http.StatusNotFound, http.StatusInternalServerError} { + t.Run(http.StatusText(status), func(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + img := workerImage(t) + mirror.push(t, workerRefPath, img) + digest := upstream.push(t, workerRefPath, img) + layer := mirror.breakLayer(t, img, status) + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + id, err := pullAll(r, upstream.host+workerRefPath) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + mirror.mu.Lock() + headed := slices.ContainsFunc(mirror.heads, func(p string) bool { return strings.HasSuffix(p, layer) }) + mirror.mu.Unlock() + if !headed { + t.Errorf("the mirror received no HEAD for %s: %v", layer, mirror.heads) + } + if len(upstream.seen()) == 0 { + t.Error("the registry was not tried") + } + }) + } +} + +func TestRemotePullNamesTheLayerTheMirrorMisses(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + img := workerImage(t) + mirror.push(t, workerRefPath, img) + layer := mirror.breakLayer(t, img, http.StatusNotFound) + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + _, err := pullAll(r, upstream.host+workerRefPath) + if !errors.Is(err, ErrPull) { + t.Fatalf("err = %v, want ErrPull", err) + } + for _, want := range []string{"the mirror misses a layer", layer, "NAME_UNKNOWN"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("err = %v, want it to carry %q", err, want) + } + } +} + +// Every HEAD the mirror receives carries ns, like the other requests. +func TestRemotePullChecksTheLayersWithNS(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + mirror.push(t, workerRefPath, workerImage(t)) + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + if _, err := pullAll(r, upstream.host+workerRefPath); err != nil { + t.Fatal(err) + } + mirror.mu.Lock() + blobHeads := slices.ContainsFunc(mirror.heads, func(p string) bool { return strings.Contains(p, "/blobs/") }) + mirror.mu.Unlock() + if !blobHeads { + t.Errorf("Pull sent no HEAD for a layer to the mirror: %v", mirror.heads) + } + for _, ns := range mirror.seen() { + if ns != upstream.host { + t.Errorf("the mirror received ns=%q, want %q", ns, upstream.host) + } + } +} + // counting counts the requests to host that reach the transport, sent or not: // a cancelled context stops a request before the server sees it. type counting struct { @@ -1876,6 +1978,30 @@ func TestOnMirrorMarksAListedMirrorInsecure(t *testing.T) { } } +// Resolve reads no layer, so it does not check the mirror holds them: an +// adoption check that the mirror's configuration answers needs no registry. +func TestRemoteResolveTrustsAMirrorMissingALayer(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + img := workerImage(t) + digest := mirror.push(t, workerRefPath, img) + mirror.breakLayer(t, img, http.StatusNotFound) + upstream.srv.Close() + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + id, err := r.Resolve(context.Background(), upstream.host+workerRefPath) + if err != nil { + t.Fatal(err) + } + if id.Digest != digest { + t.Errorf("digest = %s, want %s", id.Digest, digest) + } + mirror.mu.Lock() + defer mirror.mu.Unlock() + if slices.ContainsFunc(mirror.heads, func(p string) bool { return strings.Contains(p, "/blobs/") }) { + t.Errorf("Resolve sent a HEAD for a layer: %v", mirror.heads) + } +} + // roundTripFunc records the request it is given. type roundTripFunc func(*http.Request) (*http.Response, error) From a57971df484e9b0c4e66e687d9216d10a7367767 Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:07:43 +0100 Subject: [PATCH 5/8] feat(puller): log the mirror passed over when the registry answers When the registry serves the image after the mirror failed, nothing failed, so there is no error to return. Without a log, a mirror that always fails goes unnoticed until the node loses the registry too. It is logged through the logr logger of the context, and agent/AGENTS.md notes this one exception to "packages return errors". Refs: MK8S-553 --- agent/AGENTS.md | 4 ++- agent/internal/puller/puller.go | 5 ++++ agent/internal/puller/puller_test.go | 44 ++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 1 deletion(-) diff --git a/agent/AGENTS.md b/agent/AGENTS.md index a08adca..a6cf125 100644 --- a/agent/AGENTS.md +++ b/agent/AGENTS.md @@ -88,7 +88,9 @@ converges that node for real. of the calls, key-value pairs balanced, not the wording, so follow Kubernetes' own convention for messages: a capital first letter, no trailing period, the object type named. The reconciler logs outcomes, the packages it - calls return errors. + calls return errors. One exception: the puller logs a mirror it passed over + when the registry served the image, with the logr logger of the context. + The pull worked, so there is no error to return. - **Node labels**: patched, never updated wholesale. Several agents write the same Node object at once, and everything they did not touch has to survive. - **Vendor neutrality**: this code knows about Kubernetes and containerd, never diff --git a/agent/internal/puller/puller.go b/agent/internal/puller/puller.go index 155a0b9..14565ab 100644 --- a/agent/internal/puller/puller.go +++ b/agent/internal/puller/puller.go @@ -14,6 +14,7 @@ import ( "slices" "strings" + "github.com/go-logr/logr" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/partial" @@ -262,6 +263,10 @@ func (r Remote) open(ctx context.Context, ref string, layers bool) (v1.Image, Im errors.WithDetail("neither the mirror nor the registry served the image"), errors.WithProperty("source", ref), errors.WithProperty("mirror", r.mirror.RegistryStr())) } + // Logged, not returned: the registry answered. Without it, a mirror that + // always fails goes unnoticed until the node loses the registry too. + logr.FromContextOrDiscard(ctx).Info("Mirror failed, resolved the image from the registry", + "source", ref, "mirror", r.mirror.RegistryStr(), "reason", mirrorErr.Error()) return img, id, nil } diff --git a/agent/internal/puller/puller_test.go b/agent/internal/puller/puller_test.go index ec564b9..a122335 100644 --- a/agent/internal/puller/puller_test.go +++ b/agent/internal/puller/puller_test.go @@ -27,6 +27,8 @@ import ( "github.com/google/go-containerregistry/pkg/v1/tarball" + "github.com/go-logr/logr" + "github.com/go-logr/logr/funcr" "github.com/google/go-containerregistry/pkg/crane" "github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/registry" @@ -1899,6 +1901,48 @@ func TestRemotePullChecksTheLayersWithNS(t *testing.T) { } } +// logged returns a context whose logr logger appends each line to the +// returned buffer. +func logged() (context.Context, *strings.Builder) { + var buf strings.Builder + var mu sync.Mutex + l := funcr.New(func(_, args string) { + mu.Lock() + defer mu.Unlock() + buf.WriteString(args + "\n") + }, funcr.Options{}) + return logr.NewContext(context.Background(), l), &buf +} + +// A mirror passed over is logged, since the pull itself succeeds. A mirror +// that answers is not. +func TestRemotePullLogsAMirrorItPassedOver(t *testing.T) { + mirror, upstream := newMirrorTest(t), newMirrorTest(t) + img := workerImage(t) + mirror.push(t, workerRefPath, img) + upstream.push(t, workerRefPath, img) + r := mirrored(t, loopbackTransport("", t), mirror.host, mirror.host, upstream.host) + + ctx, buf := logged() + if _, err := r.Resolve(ctx, upstream.host+workerRefPath); err != nil { + t.Fatal(err) + } + if buf.Len() != 0 { + t.Errorf("a mirror that answered was logged: %s", buf.String()) + } + + mirror.srv.Close() + ctx, buf = logged() + if _, err := r.Resolve(ctx, upstream.host+workerRefPath); err != nil { + t.Fatal(err) + } + for _, want := range []string{"Mirror failed", mirror.host, "connection refused"} { + if !strings.Contains(buf.String(), want) { + t.Errorf("log = %q, want it to carry %q", buf.String(), want) + } + } +} + // counting counts the requests to host that reach the transport, sent or not: // a cancelled context stops a request before the server sees it. type counting struct { From d355c253b9ccf86f87067c9f9331b2a6998992bc Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:07:50 +0100 Subject: [PATCH 6/8] feat(agent): add --mirror to the agent The agent takes the mirror as a flag and logs it at startup. Its README says what the flag does and points to the design for the rest. Refs: MK8S-553 --- agent/README.md | 8 ++++++++ agent/cmd/manager/main.go | 13 +++++++++++-- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/agent/README.md b/agent/README.md index 8c81191..4c5a053 100644 --- a/agent/README.md +++ b/agent/README.md @@ -170,6 +170,14 @@ warning at startup. It goes with `--ca-file`, which covers the registries that serve TLS, but not with `--insecure-skip-tls-verify`. No manifest here sets it. +`--mirror=` names a registry every source is pulled from first, +as a containerd mirror is, so the `ImageCache` sources keep the real image +name, such as `ghcr.io/scality/x:1.0`. When the mirror fails or misses a +layer, the agent pulls from the registry the source names and logs the +mirror's failure. The mirror takes `--ca-file` like any registry, and needs +`--plain-http-registry` if it serves plain HTTP. How it works and what it +trusts is in "Image pulling" in [DESIGN.md](DESIGN.md). + Leader election is deliberately absent. Every agent converges the node it runs on, so there is nothing to elect a leader for. diff --git a/agent/cmd/manager/main.go b/agent/cmd/manager/main.go index b32e076..2976627 100644 --- a/agent/cmd/manager/main.go +++ b/agent/cmd/manager/main.go @@ -85,6 +85,7 @@ func main() { var caFile string var skipVerify bool var plainHTTPRegistries stringList + var mirror string var tlsOpts []func(*tls.Config) flag.StringVar(&metricsAddr, "metrics-bind-address", "0", "The address the metrics endpoint binds to. "+ "Use :8443 for HTTPS or :8080 for HTTP, or leave as 0 to disable the metrics service.") @@ -117,6 +118,10 @@ func main() { flag.Var(&plainHTTPRegistries, "plain-http-registry", "A registry, as host[:port] exactly as the sources name it, the agent may reach over plain HTTP. "+ "Repeatable. Excludes --insecure-skip-tls-verify.") + flag.StringVar(&mirror, "mirror", "", + "A registry, as host[:port], every source is pulled from first. The registry the source "+ + "names is tried next, when the mirror fails. Reached over plain HTTP only if it is "+ + "listed with --plain-http-registry.") opts := zap.Options{ Development: true, } @@ -225,10 +230,10 @@ func main() { // Checked before anything starts: an unusable CA would otherwise surface // as a failed pull on every node and every resource. remote, err := puller.NewRemote(puller.TLS{ - CAFile: caFile, SkipVerify: skipVerify, PlainHTTPRegistries: plainHTTPRegistries, + CAFile: caFile, SkipVerify: skipVerify, PlainHTTPRegistries: plainHTTPRegistries, Mirror: mirror, }) if err != nil { - setupLog.Error(err, "unable to set up registry TLS") + setupLog.Error(err, "unable to set up the registry access") os.Exit(1) } if skipVerify { @@ -241,6 +246,10 @@ func main() { "registries", []string(plainHTTPRegistries)) } + if mirror != "" { + setupLog.Info("sources are pulled from the mirror first", "mirror", mirror) + } + fw, err := controller.NewFSWatcher(nodeName) if err != nil { setupLog.Error(err, "unable to create filesystem watcher") From 77cd5581fa9ae13ceb5e616d2858a3611d7e21fa Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:07:58 +0100 Subject: [PATCH 7/8] test(e2e): pull through a mirror on kind A spec pulls a source the registry does not hold through the mirror, then falls back on the registry when the mirror loses a layer and when it is stopped, and checks the agent logs the mirror it passed over. registryHost names the test registries in one place, and deployRegistry enables deletes so a spec can remove a blob without a restart. Refs: MK8S-553 --- agent/test/e2e/e2e_test.go | 110 ++++++++++++++++++++++++++++++++++--- 1 file changed, 103 insertions(+), 7 deletions(-) diff --git a/agent/test/e2e/e2e_test.go b/agent/test/e2e/e2e_test.go index 6abc688..c06c27d 100644 --- a/agent/test/e2e/e2e_test.go +++ b/agent/test/e2e/e2e_test.go @@ -82,6 +82,15 @@ const syncedName = "imagecache-e2e-synced" // ClusterIP, a private address the library also tries over plain HTTP. const plainIPName = "imagecache-e2e-plain-ip" +// mirroredName, partialName and fallbackName are the ImageCaches pulled with +// --mirror: the first from the mirror, the second from the registry while the +// mirror misses a layer, the third from the registry once the mirror is down. +const ( + mirroredName = "imagecache-e2e-mirrored" + partialName = "imagecache-e2e-partial" + fallbackName = "imagecache-e2e-fallback" +) + // tlsName is the ImageCache that pulls from the registry signed by a // throwaway CA, to exercise --ca-file through the shipped patch. const tlsName = "imagecache-e2e-tls" @@ -415,6 +424,82 @@ spec: }).Should(BeFalse()) }) + It("should pull through the mirror first, then from the registry when the mirror misses a layer or is down", func() { + deployRegistry("mirror", "") + deployRegistry("upstream", "") + // The registry has nothing yet: a pull that works went through + // the mirror. + digest := pushCarrier("mirror", nil) + + By("restarting the agent with the mirror") + patchAgent("--type=json", fmt.Sprintf(`-p=[`+ + `{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--plain-http-registry=%[1]s"},`+ + `{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--plain-http-registry=%[2]s"},`+ + `{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--mirror=%[1]s"}]`, + registryHost("mirror"), registryHost("upstream"))) + + worker := utils.WorkerNode() + expectSynced := func(name string) { + By("waiting for " + name + " to be synced on the worker") + Eventually(func(g Gomega) { + labels, err := nodeLabels(worker) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(labels).To(HaveKeyWithValue(labelKey(name), "synced")) + }).Should(Succeed()) + expectExtracted(worker, cachePath+"/"+name, digest) + } + DeferCleanup(func() { + cmd := exec.Command("kubectl", "delete", "imagecache", mirroredName, partialName, fallbackName, + "--ignore-not-found") + _, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to delete the ImageCaches") + }) + + By("creating an ImageCache whose source names the registry") + applyImageCache(mirroredName, worker, "upstream") + expectSynced(mirroredName) + + By("pushing the image to the registry and deleting its layer from the mirror") + Expect(pushCarrier("upstream", nil)).To(Equal(digest)) + layers, err := carrierImage(carrierBody).Layers() + Expect(err).NotTo(HaveOccurred()) + Expect(layers).To(HaveLen(1)) + layer, err := layers[0].Digest() + Expect(err).NotTo(HaveOccurred()) + local := portForward(registryNamespace, "svc/mirror", 5000) + req, err := http.NewRequest(http.MethodDelete, "http://"+local+"/v2/e2e/carrier/blobs/"+layer.String(), nil) + Expect(err).NotTo(HaveOccurred()) + resp, err := http.DefaultClient.Do(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.Body.Close()).To(Succeed()) + Expect(resp.StatusCode).To(Equal(http.StatusAccepted), "The mirror did not delete the layer") + + By("creating an ImageCache the mirror can resolve but not serve whole") + applyImageCache(partialName, worker, "upstream") + expectSynced(partialName) + By("checking that the agent logged the mirror it passed over") + Eventually(func() (string, error) { + cmd := exec.Command("kubectl", "logs", "-l", agentSelector, "-n", namespace, "--tail=-1") + return utils.Run(cmd) + }).Should(And(ContainSubstring("Mirror failed, resolved the image from the registry"), + ContainSubstring("the mirror misses a layer"))) + + By("stopping the mirror") + cmd := exec.Command("kubectl", "scale", "deployment/mirror", "-n", registryNamespace, "--replicas=0") + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to stop the mirror") + // Both hold the same digest: a pod still terminating could serve + // the pull and hide a broken fallback. + cmd = exec.Command("kubectl", "wait", "--for=delete", "pod", "-l", "app=mirror", + "-n", registryNamespace, "--timeout=2m") + _, err = utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "The mirror did not stop") + + By("creating a second ImageCache, pulled from the registry") + applyImageCache(fallbackName, worker, "upstream") + expectSynced(fallbackName) + }) + It("should refuse a registry signed by an unknown CA, then pull once the registry CA patch is applied", func() { ca, cert, key := newRegistryCerts("registry-tls." + registryNamespace + ".svc.cluster.local") deployRegistry("registry-tls", tlsSecret("registry-tls", cert, key)) @@ -546,7 +631,7 @@ func patchAgent(args ...string) { // allowPlainHTTP restarts the agent with the named in-cluster registry listed // in --plain-http-registry, written as applyImageCache's sources name it. func allowPlainHTTP(registry string) { - listPlainHTTP(fmt.Sprintf("%s.%s.svc.cluster.local:5000", registry, registryNamespace)) + listPlainHTTP(registryHost(registry)) } // listPlainHTTP restarts the agent with host listed in --plain-http-registry. @@ -562,10 +647,16 @@ func waitAgentRollout() { Expect(err).NotTo(HaveOccurred(), "The agent did not roll out") } +// registryHost is the host[:port] of the named in-cluster registry, as the +// sources and the agent flags name it. +func registryHost(registry string) string { + return fmt.Sprintf("%s.%s.svc.cluster.local:5000", registry, registryNamespace) +} + // applyImageCache creates an ImageCache that selects one node and pulls the // carrier image from the named in-cluster registry. func applyImageCache(name, node, registry string) { - applyImageCacheFrom(name, node, fmt.Sprintf("%s.%s.svc.cluster.local:5000/e2e/carrier:1", registry, registryNamespace)) + applyImageCacheFrom(name, node, registryHost(registry)+"/e2e/carrier:1") } // applyImageCacheFrom creates an ImageCache that selects one node and pulls @@ -615,13 +706,18 @@ func expectExtracted(node, dir string, digest v1.Hash) { // deployRegistry deploys a single-replica registry and its Service, both // called name, and waits for it. Given a TLS Secret manifest from tlsSecret, -// it applies it and the registry serves HTTPS with that certificate. +// it applies it and the registry serves HTTPS with that certificate. Deletes +// are enabled, so a spec can make a registry lose a blob without restarting +// it, which would empty its storage. func deployRegistry(name, secret string) { By("deploying the " + name + " registry in the cluster") - tlsEnv, tlsMount, tlsVolume, scheme := "", "", "", "HTTP" - if secret != "" { - tlsEnv = ` + tlsMount, tlsVolume, scheme := "", "", "HTTP" + env := ` env: + - name: REGISTRY_STORAGE_DELETE_ENABLED + value: "true"` + if secret != "" { + env += ` - name: REGISTRY_HTTP_TLS_CERTIFICATE value: /certs/tls.crt - name: REGISTRY_HTTP_TLS_KEY @@ -678,7 +774,7 @@ spec: app: %[2]s ports: - port: 5000 -`, registryNamespace, name, secret, registryImage, tlsEnv, tlsMount, scheme, tlsVolume) +`, registryNamespace, name, secret, registryImage, env, tlsMount, scheme, tlsVolume) cmd := exec.Command("kubectl", "apply", "-f", "-") cmd.Stdin = strings.NewReader(manifest) _, err := utils.Run(cmd) From 1482aab0ebbdd6e45f580b56a05adac5a04c7fa5 Mon Sep 17 00:00:00 2001 From: Alex Rodriguez <131964409+ezekiel-alexrod@users.noreply.github.com> Date: Fri, 27 Nov 2026 10:08:05 +0100 Subject: [PATCH 8/8] feat(cli): add --mirror to imagecachectl imagecachectl import takes the same mirror. Its --plain-http then goes to the mirror, and pairs with --ca-file, which covers the registry the source names. The command warns about a mirror it passed over, and names the mirror in its plain HTTP warning. Refs: MK8S-553 --- README.md | 11 +++- agent/internal/cli/cli.go | 56 +++++++++++++--- agent/internal/cli/cli_test.go | 115 ++++++++++++++++++++++++++++++++- 3 files changed, 166 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 163953d..013a2cd 100644 --- a/README.md +++ b/README.md @@ -178,10 +178,15 @@ by a private CA, on top of the system ones. It is checked on every run, and never read for an archive. `--insecure-skip-tls-verify` accepts any certificate instead, for a test cluster only, and prints a warning. `--plain-http` reaches a registry that serves plain HTTP, and prints a warning -too. It applies to the registry of the source only, and excludes the two -certificate flags. Without it, the registry is reached over HTTPS only, even -on a private or loopback IP address. The agent takes a list instead, +too. It applies to the registry of the source only, or to the mirror when +`--mirror` is given, and excludes the two certificate flags. With `--mirror`, +it goes with `--ca-file`, which then covers the registry the source names. +Without it, the registry is reached over HTTPS only, even on a private or +loopback IP address. The agent takes a list instead, `--plain-http-registry`, see [agent/README.md](agent/README.md). +`--mirror=` pulls the source from that registry first, and falls +back on the registry the source names, see "Image pulling" in +[agent/DESIGN.md](agent/DESIGN.md). The import refuses to replace a directory without a sentinel. The command runs as root, so a wrong name or cache path that lands on a directory the store did diff --git a/agent/internal/cli/cli.go b/agent/internal/cli/cli.go index 8e371ee..0fd9d08 100644 --- a/agent/internal/cli/cli.go +++ b/agent/internal/cli/cli.go @@ -12,6 +12,8 @@ import ( "path/filepath" "strings" + "github.com/go-logr/logr" + "github.com/go-logr/logr/funcr" imgname "github.com/google/go-containerregistry/pkg/name" "github.com/scality/go-errors" "github.com/spf13/cobra" @@ -43,7 +45,11 @@ const importLong = `Fills the image cache with the archives a boot cache image c is either the path of a docker archive or the reference of an image in a registry. It is a path when it starts with a separator or a dot, or ends in .tar, and a reference otherwise: the shape of what you pass decides, not -what is on disk.` +what is on disk. + +--plain-http excludes --insecure-skip-tls-verify. It also excludes --ca-file, +unless --mirror is given: the plain HTTP then goes to the mirror, and the CA +covers the registry the source names.` const importExample = ` imagecachectl import --name worker-1-0-0 registry.example.com/boot-cache-worker:1.0.0 imagecachectl import --name worker-1-0-0 /mnt/iso/images/boot-cache-worker.tar @@ -52,10 +58,10 @@ const importExample = ` imagecachectl import --name worker-1-0-0 registry.examp // Run executes the command line and returns the process exit code: 0 on // success, ExitInterrupted when the context was cancelled, 1 otherwise. func Run(ctx context.Context, args []string, out, errOut io.Writer) int { - var name, cachePath, caFile string + var name, cachePath, caFile, mirror string var skipVerify, plainHTTP bool importCmd := &cobra.Command{ - Use: "import --name [--cache-path ] [--ca-file | --insecure-skip-tls-verify | --plain-http] ", + Use: "import --name [--cache-path ] [--mirror ] [--ca-file | --insecure-skip-tls-verify] [--plain-http] ", Short: "Fill the image cache from a registry or a docker archive", Long: importLong, Example: importExample, @@ -74,14 +80,16 @@ func Run(ctx context.Context, args []string, out, errOut io.Writer) int { if caFile != "" && skipVerify { return errors.New("--ca-file and --insecure-skip-tls-verify exclude each other") } - if plainHTTP && caFile != "" { + // With a mirror, --plain-http goes to the mirror and --ca-file + // covers the source's registry, so the two go together. + if plainHTTP && caFile != "" && mirror == "" { return errors.New("--ca-file and --plain-http exclude each other") } if plainHTTP && skipVerify { return errors.New("--insecure-skip-tls-verify and --plain-http exclude each other") } err := do(cmd.Context(), cachePath, name, args[0], - puller.TLS{CAFile: caFile, SkipVerify: skipVerify}, plainHTTP, out, errOut) + puller.TLS{CAFile: caFile, SkipVerify: skipVerify, Mirror: mirror}, plainHTTP, out, errOut) // An interrupted run is not a failure to diagnose: the extraction // publishes by rename, so nothing half written is left behind. if errors.Is(err, context.Canceled) { @@ -98,7 +106,9 @@ func Run(ctx context.Context, args []string, out, errOut io.Writer) int { importCmd.Flags().BoolVar(&skipVerify, "insecure-skip-tls-verify", false, "accept any registry certificate, for a test cluster set up by hand only") importCmd.Flags().BoolVar(&plainHTTP, "plain-http", false, - "allow plain HTTP to the registry, for a registry without TLS") + "allow plain HTTP to the registry, for a registry without TLS: to the mirror when --mirror is given") + importCmd.Flags().StringVar(&mirror, "mirror", "", + "registry, as `host[:port]`, to pull the source from first, before the registry it names") _ = importCmd.MarkFlagRequired("name") root := &cobra.Command{ @@ -149,6 +159,10 @@ func validate(name, cachePath string) error { func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, plainHTTP bool, out, errOut io.Writer) error { store := cache.Store{} + // The puller logs a mirror it passed over. On the host, that is a warning. + ctx = logr.NewContext(ctx, funcr.New(func(_, args string) { + printf(errOut, "imagecachectl: warning: %s\n", args) + }, funcr.Options{RenderBuiltinsHook: dropLevel})) // Before the cache state, so that a CA that cannot be used is reported // on every run, including one that would have found the resource @@ -162,7 +176,11 @@ func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, pla printf(errOut, "imagecachectl: warning: the registry certificate is not verified\n") } if plainHTTP { - printf(errOut, "imagecachectl: warning: the registry may be reached over plain HTTP\n") + target := "the registry" + if tls.Mirror != "" { + target = "the mirror" + } + printf(errOut, "imagecachectl: warning: %s may be reached over plain HTTP\n", target) } } @@ -219,8 +237,9 @@ func do(ctx context.Context, cachePath, name, source string, tls puller.TLS, pla // // The TLS and plain HTTP settings only matter to a registry, so an archive // never reads them. The command pulls one source per run, so plain HTTP is -// allowed to that source's registry: the puller takes a list of registries, -// and this one is the only entry. +// allowed to one registry: the puller takes a list, and it is the only entry. +// With a mirror, that registry is the mirror, and the registry the source +// names keeps HTTPS, see "Image pulling" in agent/DESIGN.md. func pullerFor(source string, tls puller.TLS, plainHTTP bool) (puller.Puller, error) { switch { case strings.HasPrefix(source, string(os.PathSeparator)), @@ -230,9 +249,26 @@ func pullerFor(source string, tls puller.TLS, plainHTTP bool) (puller.Puller, er default: // A reference that does not parse is reported by the pull, which // names it as one. - if ref, err := imgname.ParseReference(source); plainHTTP && err == nil { + switch ref, err := imgname.ParseReference(source); { + case !plainHTTP: + // Every registry stays HTTPS only. + case tls.Mirror != "": + tls.PlainHTTPRegistries = []string{tls.Mirror} + case err == nil: tls.PlainHTTPRegistries = []string{ref.Context().RegistryStr()} } return puller.NewRemote(tls) } } + +// dropLevel leaves the log level out of a warning: the command prints every +// line at the same level, so it says nothing to the reader. +func dropLevel(kv []any) []any { + out := make([]any, 0, len(kv)) + for i := 0; i+1 < len(kv); i += 2 { + if kv[i] != "level" { + out = append(out, kv[i], kv[i+1]) + } + } + return out +} diff --git a/agent/internal/cli/cli_test.go b/agent/internal/cli/cli_test.go index ae0203b..dd84fac 100644 --- a/agent/internal/cli/cli_test.go +++ b/agent/internal/cli/cli_test.go @@ -5,6 +5,7 @@ import ( "bytes" "context" "encoding/json" + "encoding/pem" "errors" "io" "net" @@ -31,9 +32,11 @@ const ( importCmd = "import" nameFlag = "--name" helpFlag = "--help" - etcdTarPath = "images/etcd.tar" - pauseTarPath = "images/pause.tar" - SentinelName = ".image-cache-agent.json" + // cachePathFlag is spelled once for goconst, which counts it in slice literals. + cachePathFlag = "--cache-path" + etcdTarPath = "images/etcd.tar" + pauseTarPath = "images/pause.tar" + SentinelName = ".image-cache-agent.json" ) // archive writes a docker archive shaped like a boot cache image. @@ -832,3 +835,109 @@ func TestPlainHTTPIsNotAnnouncedForAnArchive(t *testing.T) { t.Errorf("stderr warns about plain HTTP for an archive: %s", errOut) } } + +// pauseContent is what the mirror serves for pause.tar. +const pauseContent = "pause" + +// The source names a registry that does not exist, so only the mirror can +// serve it. --plain-http goes to the mirror. +func TestImportThroughAMirror(t *testing.T) { + ref := served(t, map[string][]byte{pauseTarPath: []byte(pauseContent)}) + mirror, _, _ := strings.Cut(ref, "/") + cacheDir := t.TempDir() + + code, _, errOut := run(t, importCmd, nameFlag, resourceName, cachePathFlag, cacheDir, + "--plain-http", "--mirror", mirror, "registry.invalid:5000/boot-cache/worker:1.0.0") + if code != 0 { + t.Fatalf("exit = %d, want 0 (%s)", code, errOut) + } + if !strings.Contains(errOut, "the mirror may be reached over plain HTTP") { + t.Errorf("stderr does not name the mirror in the plain HTTP warning: %s", errOut) + } + got, err := os.ReadFile(filepath.Join(cacheDir, resourceName, "pause.tar")) + if err != nil { + t.Fatal(err) + } + if string(got) != pauseContent { + t.Errorf("pause.tar = %q, want %q", got, pauseContent) + } +} + +func TestMirrorThatIsNotAHostIsNamed(t *testing.T) { + for _, flags := range [][]string{{}, {"--plain-http"}} { + args := append([]string{importCmd, nameFlag, resourceName, cachePathFlag, t.TempDir(), + "--mirror", "https://registry.local"}, flags...) + code, _, errOut := run(t, append(args, "registry.local/boot-cache/worker:1.0.0")...) + if code != 1 { + t.Fatalf("%v: exit = %d, want 1 (%s)", flags, code, errOut) + } + if !strings.Contains(errOut, puller.ErrMirror.Error()) { + t.Errorf("%v: stderr = %s, want the mirror named", flags, errOut) + } + } +} + +// The pull works through the registry, so the mirror it passed over is a +// warning, not a failure. +func TestImportWarnsAboutAMirrorItPassedOver(t *testing.T) { + srv := httptest.NewTLSServer(registry.New()) + t.Cleanup(srv.Close) + img, err := crane.Image(map[string][]byte{pauseTarPath: []byte(pauseContent)}) + if err != nil { + t.Fatal(err) + } + ref := strings.TrimPrefix(srv.URL, "https://") + "/boot-cache/worker:1.0.0" + if err := crane.Push(img, ref, crane.WithTransport(srv.Client().Transport)); err != nil { + t.Fatal(err) + } + // Nothing listens on port 1. + code, _, errOut := run(t, importCmd, nameFlag, resourceName, cachePathFlag, t.TempDir(), + "--insecure-skip-tls-verify", "--mirror", "127.0.0.1:1", ref) + if code != 0 { + t.Fatalf("exit = %d, want 0 (%s)", code, errOut) + } + for _, want := range []string{"imagecachectl: warning:", "Mirror failed", "127.0.0.1:1"} { + if !strings.Contains(errOut, want) { + t.Errorf("stderr = %s, want it to carry %q", errOut, want) + } + } + if strings.Contains(errOut, `"level"`) { + t.Errorf("stderr carries the log level: %s", errOut) + } +} + +// A plain HTTP mirror with a fallback registry signed by a private CA: with +// --mirror, --plain-http and --ca-file cover different registries. +func TestPlainHTTPMirrorGoesWithACAFile(t *testing.T) { + srv := httptest.NewTLSServer(registry.New()) + t.Cleanup(srv.Close) + img, err := crane.Image(map[string][]byte{pauseTarPath: []byte(pauseContent)}) + if err != nil { + t.Fatal(err) + } + ref := strings.TrimPrefix(srv.URL, "https://") + "/boot-cache/worker:1.0.0" + if err := crane.Push(img, ref, crane.WithTransport(srv.Client().Transport)); err != nil { + t.Fatal(err) + } + caFile := filepath.Join(t.TempDir(), "ca.crt") + block := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) + if err := os.WriteFile(caFile, block, 0o600); err != nil { + t.Fatal(err) + } + cacheDir := t.TempDir() + + // Nothing listens on port 1: the pull falls back on the registry, which + // only the CA file lets the command trust. + code, _, errOut := run(t, importCmd, nameFlag, resourceName, cachePathFlag, cacheDir, + "--mirror", "127.0.0.1:1", "--plain-http", "--ca-file", caFile, ref) + if code != 0 { + t.Fatalf("exit = %d, want 0 (%s)", code, errOut) + } + got, err := os.ReadFile(filepath.Join(cacheDir, resourceName, "pause.tar")) + if err != nil { + t.Fatal(err) + } + if string(got) != pauseContent { + t.Errorf("pause.tar = %q, want %q", got, pauseContent) + } +}