11package resolver
22
33import (
4+ "bytes"
45 "compress/gzip"
56 "context"
67 "encoding/json"
78 "fmt"
9+ "io"
10+ "net"
811 "net/http"
912 "net/http/httptest"
1013 "strings"
1114 "sync/atomic"
1215 "testing"
16+ "time"
1317
1418 "github.com/containerd/containerd/v2/core/content"
1519 "github.com/containerd/containerd/v2/core/leases"
@@ -283,16 +287,27 @@ type testPullRegistry struct {
283287 manifestGETs atomic.Int32
284288 layerGETs atomic.Int32
285289 layerAcceptEncoding atomic.Pointer [string ]
290+ // resetNextLayerGET makes the next layer GET end in a TCP reset partway
291+ // through its body; layerResets counts the resets sent.
292+ resetNextLayerGET atomic.Bool
293+ layerResets atomic.Int32
286294}
287295
288- func (r * testPullRegistry ) manifestRequests () int32 {
289- return r .manifestHEADs .Load () + r .manifestGETs .Load ()
296+ func (registry * testPullRegistry ) manifestRequests () int32 {
297+ return registry .manifestHEADs .Load () + registry .manifestGETs .Load ()
290298}
291299
292300func newTestPullRegistry (t * testing.T , image * testPullImage ) * testPullRegistry {
293301 t .Helper ()
294302 registry := & testPullRegistry {}
295- server := httptest .NewServer (http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
303+ server := httptest .NewServer (registry .handler (image ))
304+ t .Cleanup (server .Close )
305+ registry .host = strings .TrimPrefix (server .URL , "http://" )
306+ return registry
307+ }
308+
309+ func (registry * testPullRegistry ) handler (image * testPullImage ) http.Handler {
310+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
296311 switch {
297312 case r .URL .Path == "/v2/" :
298313 w .WriteHeader (http .StatusOK )
@@ -316,6 +331,19 @@ func newTestPullRegistry(t *testing.T, image *testPullImage) *testPullRegistry {
316331 case r .URL .Path == "/v2/test/image/blobs/" + image .layer .Digest .String ():
317332 if r .Method == http .MethodGet {
318333 registry .layerGETs .Add (1 )
334+ if registry .resetNextLayerGET .CompareAndSwap (true , false ) {
335+ if resetTestRegistryResponse (w , image .layer , image .layerBytes ) {
336+ registry .layerResets .Add (1 )
337+ }
338+ return
339+ }
340+ if r .Header .Get ("Range" ) != "" {
341+ // A resumed fetch gets the rest of the blob, as registries serve it.
342+ w .Header ().Set ("Docker-Content-Digest" , image .layer .Digest .String ())
343+ w .Header ().Set ("Content-Type" , image .layer .MediaType )
344+ http .ServeContent (w , r , "" , time.Time {}, bytes .NewReader (image .layerBytes ))
345+ return
346+ }
319347 encoding := r .Header .Get ("Accept-Encoding" )
320348 registry .layerAcceptEncoding .Store (& encoding )
321349 if encoding != "identity" {
@@ -330,10 +358,7 @@ func newTestPullRegistry(t *testing.T, image *testPullImage) *testPullRegistry {
330358 default :
331359 http .NotFound (w , r )
332360 }
333- }))
334- t .Cleanup (server .Close )
335- registry .host = strings .TrimPrefix (server .URL , "http://" )
336- return registry
361+ })
337362}
338363
339364func serveTestRegistryManifest (w http.ResponseWriter , r * http.Request , desc ocispecs.Descriptor , payload []byte ) {
@@ -348,6 +373,24 @@ func serveTestRegistryManifest(w http.ResponseWriter, r *http.Request, desc ocis
348373 http .Error (w , "manifest type not accepted: " + desc .MediaType , http .StatusNotFound )
349374}
350375
376+ // resetTestRegistryResponse sends the headers and half the body of payload,
377+ // then resets the TCP connection, as a registry dropping a connection
378+ // partway through a blob does. It reports whether the reset was sent.
379+ func resetTestRegistryResponse (w http.ResponseWriter , desc ocispecs.Descriptor , payload []byte ) bool {
380+ conn , buf , err := http .NewResponseController (w ).Hijack ()
381+ if err != nil {
382+ return false
383+ }
384+ defer conn .Close ()
385+ fmt .Fprintf (buf , "HTTP/1.1 200 OK\r \n Docker-Content-Digest: %s\r \n Content-Type: %s\r \n Content-Length: %d\r \n \r \n " , desc .Digest , desc .MediaType , len (payload ))
386+ _ , _ = buf .Write (payload [:len (payload )/ 2 ])
387+ if err := buf .Flush (); err != nil {
388+ return false
389+ }
390+ tcp , ok := conn .(* net.TCPConn )
391+ return ok && tcp .SetLinger (0 ) == nil
392+ }
393+
351394func newTestResolver (t * testing.T , host string , store content.Store ) * Resolver {
352395 t .Helper ()
353396 return newTestResolverWithLeases (t , host , store , newTestLeaseManager ())
@@ -374,6 +417,102 @@ func newTestResolverWithLeases(t *testing.T, host string, store content.Store, l
374417 return rslvr
375418}
376419
420+ // A registry that resets the connection partway through a layer, as
421+ // mcr.microsoft.com sometimes does, does not fail the pull: the layer is
422+ // fetched again.
423+ func TestPullRetriesLayerAfterConnectionReset (t * testing.T ) {
424+ ctx := t .Context ()
425+ s := seedPinnedMetadata (t , false )
426+ s .registry .resetNextLayerGET .Store (true )
427+
428+ pulled , err := s .resolver .Pull (ctx , s .ref , s .opts )
429+ require .NoError (t , err )
430+ t .Cleanup (func () { require .NoError (t , pulled .Release (context .WithoutCancel (ctx ))) })
431+ require .Equal (t , int32 (1 ), s .registry .layerResets .Load (), "the first layer GET was reset partway through" )
432+ require .Equal (t , int32 (2 ), s .registry .layerGETs .Load (), "the layer was fetched again" )
433+ require .Len (t , pulled .Layers , 1 )
434+ actual , err := content .ReadBlob (ctx , s .store , s .image .layer )
435+ require .NoError (t , err )
436+ require .Equal (t , s .image .layerBytes , actual )
437+ }
438+
439+ // A registry whose TLS handshake times out on the manifest request, as
440+ // mcr.microsoft.com's sometimes does, does not fail resolving the image: the
441+ // request is sent again.
442+ func TestResolveRetriesManifestAfterTLSHandshakeTimeout (t * testing.T ) {
443+ ctx := t .Context ()
444+ platform := ocispecs.Platform {OS : "linux" , Architecture : "amd64" }
445+ image := newTestPullImage (t , false , platform )
446+ registry := & testPullRegistry {}
447+ server := httptest .NewUnstartedServer (registry .handler (image ))
448+ listener := & stallFirstHandshakeListener {Listener : server .Listener }
449+ server .Listener = listener
450+ server .StartTLS ()
451+ t .Cleanup (server .Close )
452+ registry .host = strings .TrimPrefix (server .URL , "https://" )
453+
454+ client := server .Client ()
455+ client .Transport .(* http.Transport ).TLSHandshakeTimeout = 100 * time .Millisecond
456+ store , err := localcontentstore .NewLabeledStore (t .TempDir (), newTestContentLabelStore ())
457+ require .NoError (t , err )
458+ rslvr := New (Opts {
459+ Hosts : func (domain string ) ([]docker.RegistryHost , error ) {
460+ return []docker.RegistryHost {{
461+ Client : client ,
462+ Scheme : "https" ,
463+ Host : domain ,
464+ Path : "/v2" ,
465+ Capabilities : docker .HostCapabilityPull | docker .HostCapabilityResolve ,
466+ }}, nil
467+ },
468+ ContentStore : store ,
469+ LeaseManager : newTestLeaseManager (),
470+ })
471+ t .Cleanup (func () { require .NoError (t , rslvr .Close ()) })
472+
473+ _ , dgst , configBytes , err := rslvr .ResolveImageConfig (ctx , registry .host + "/test/image:latest" , ResolveImageConfigOpts {Platform : & platform })
474+ require .NoError (t , err )
475+ require .True (t , listener .stalled .Load (), "the first TLS handshake stalled" )
476+ require .Equal (t , int32 (1 ), registry .manifestHEADs .Load (), "only the retried manifest request got through" )
477+ require .Equal (t , image .root .Digest , dgst )
478+ require .JSONEq (t , string (image .configBytes ), string (configBytes ))
479+ }
480+
481+ // A missing image is not a network error, so resolving it fails at once.
482+ func TestResolveDoesNotRetryMissingManifest (t * testing.T ) {
483+ ctx := t .Context ()
484+ platform := ocispecs.Platform {OS : "linux" , Architecture : "amd64" }
485+ registry := newTestPullRegistry (t , newTestPullImage (t , false , platform ))
486+ store , err := localcontentstore .NewLabeledStore (t .TempDir (), newTestContentLabelStore ())
487+ require .NoError (t , err )
488+ rslvr := newTestResolver (t , registry .host , store )
489+
490+ _ , _ , err = rslvr .ResolveImageDigest (ctx , registry .host + "/test/image:missing" , ResolveImageDigestOpts {})
491+ require .True (t , cerrdefs .IsNotFound (err ), "got %v" , err )
492+ require .Equal (t , int32 (1 ), registry .manifestHEADs .Load ())
493+ }
494+
495+ // stallFirstHandshakeListener never answers the first connection's TLS
496+ // handshake, so the client's handshake times out.
497+ type stallFirstHandshakeListener struct {
498+ net.Listener
499+ stalled atomic.Bool
500+ }
501+
502+ func (l * stallFirstHandshakeListener ) Accept () (net.Conn , error ) {
503+ for {
504+ conn , err := l .Listener .Accept ()
505+ if err != nil || ! l .stalled .CompareAndSwap (false , true ) {
506+ return conn , err
507+ }
508+ // Read until the client gives up and closes the connection.
509+ go func () {
510+ defer conn .Close ()
511+ _ , _ = io .Copy (io .Discard , conn )
512+ }()
513+ }
514+ }
515+
377516// A pinned image whose blobs are all local is pulled from the content store,
378517// unless one goes before the pull's lease holds it, as a prune's collection
379518// removes an unleased blob: the pull then reads the image from the registry,
0 commit comments