github.com/rawahars/moby@v24.0.4+incompatible/distribution/xfer/download_test.go (about)

     1  package xfer // import "github.com/docker/docker/distribution/xfer"
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"errors"
     7  	"fmt"
     8  	"io"
     9  	"runtime"
    10  	"sync/atomic"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/docker/distribution"
    15  	"github.com/docker/docker/image"
    16  	"github.com/docker/docker/layer"
    17  	"github.com/docker/docker/pkg/progress"
    18  	"github.com/opencontainers/go-digest"
    19  	"gotest.tools/v3/assert"
    20  )
    21  
    22  const maxDownloadConcurrency = 3
    23  
    24  type mockLayer struct {
    25  	layerData bytes.Buffer
    26  	diffID    layer.DiffID
    27  	chainID   layer.ChainID
    28  	parent    layer.Layer
    29  }
    30  
    31  func (ml *mockLayer) TarStream() (io.ReadCloser, error) {
    32  	return io.NopCloser(bytes.NewBuffer(ml.layerData.Bytes())), nil
    33  }
    34  
    35  func (ml *mockLayer) TarStreamFrom(layer.ChainID) (io.ReadCloser, error) {
    36  	return nil, fmt.Errorf("not implemented")
    37  }
    38  
    39  func (ml *mockLayer) ChainID() layer.ChainID {
    40  	return ml.chainID
    41  }
    42  
    43  func (ml *mockLayer) DiffID() layer.DiffID {
    44  	return ml.diffID
    45  }
    46  
    47  func (ml *mockLayer) Parent() layer.Layer {
    48  	return ml.parent
    49  }
    50  
    51  func (ml *mockLayer) Size() int64 {
    52  	return 0
    53  }
    54  
    55  func (ml *mockLayer) DiffSize() int64 {
    56  	return 0
    57  }
    58  
    59  func (ml *mockLayer) Metadata() (map[string]string, error) {
    60  	return make(map[string]string), nil
    61  }
    62  
    63  type mockLayerStore struct {
    64  	layers map[layer.ChainID]*mockLayer
    65  }
    66  
    67  func createChainIDFromParent(parent layer.ChainID, dgsts ...layer.DiffID) layer.ChainID {
    68  	if len(dgsts) == 0 {
    69  		return parent
    70  	}
    71  	if parent == "" {
    72  		return createChainIDFromParent(layer.ChainID(dgsts[0]), dgsts[1:]...)
    73  	}
    74  	// H = "H(n-1) SHA256(n)"
    75  	dgst := digest.FromBytes([]byte(string(parent) + " " + string(dgsts[0])))
    76  	return createChainIDFromParent(layer.ChainID(dgst), dgsts[1:]...)
    77  }
    78  
    79  func (ls *mockLayerStore) Map() map[layer.ChainID]layer.Layer {
    80  	layers := map[layer.ChainID]layer.Layer{}
    81  
    82  	for k, v := range ls.layers {
    83  		layers[k] = v
    84  	}
    85  
    86  	return layers
    87  }
    88  
    89  func (ls *mockLayerStore) Register(reader io.Reader, parentID layer.ChainID) (layer.Layer, error) {
    90  	return ls.RegisterWithDescriptor(reader, parentID, distribution.Descriptor{})
    91  }
    92  
    93  func (ls *mockLayerStore) RegisterWithDescriptor(reader io.Reader, parentID layer.ChainID, _ distribution.Descriptor) (layer.Layer, error) {
    94  	var (
    95  		parent layer.Layer
    96  		err    error
    97  	)
    98  
    99  	if parentID != "" {
   100  		parent, err = ls.Get(parentID)
   101  		if err != nil {
   102  			return nil, err
   103  		}
   104  	}
   105  
   106  	l := &mockLayer{parent: parent}
   107  	_, err = l.layerData.ReadFrom(reader)
   108  	if err != nil {
   109  		return nil, err
   110  	}
   111  	l.diffID = layer.DiffID(digest.FromBytes(l.layerData.Bytes()))
   112  	l.chainID = createChainIDFromParent(parentID, l.diffID)
   113  
   114  	ls.layers[l.chainID] = l
   115  	return l, nil
   116  }
   117  
   118  func (ls *mockLayerStore) Get(chainID layer.ChainID) (layer.Layer, error) {
   119  	l, ok := ls.layers[chainID]
   120  	if !ok {
   121  		return nil, layer.ErrLayerDoesNotExist
   122  	}
   123  	return l, nil
   124  }
   125  
   126  func (ls *mockLayerStore) Release(l layer.Layer) ([]layer.Metadata, error) {
   127  	return []layer.Metadata{}, nil
   128  }
   129  func (ls *mockLayerStore) CreateRWLayer(string, layer.ChainID, *layer.CreateRWLayerOpts) (layer.RWLayer, error) {
   130  	return nil, errors.New("not implemented")
   131  }
   132  
   133  func (ls *mockLayerStore) GetRWLayer(string) (layer.RWLayer, error) {
   134  	return nil, errors.New("not implemented")
   135  }
   136  
   137  func (ls *mockLayerStore) ReleaseRWLayer(layer.RWLayer) ([]layer.Metadata, error) {
   138  	return nil, errors.New("not implemented")
   139  }
   140  func (ls *mockLayerStore) GetMountID(string) (string, error) {
   141  	return "", errors.New("not implemented")
   142  }
   143  
   144  func (ls *mockLayerStore) Cleanup() error {
   145  	return nil
   146  }
   147  
   148  func (ls *mockLayerStore) DriverStatus() [][2]string {
   149  	return [][2]string{}
   150  }
   151  
   152  func (ls *mockLayerStore) DriverName() string {
   153  	return "mock"
   154  }
   155  
   156  type mockDownloadDescriptor struct {
   157  	currentDownloads *int32
   158  	id               string
   159  	diffID           layer.DiffID
   160  	registeredDiffID layer.DiffID
   161  	expectedDiffID   layer.DiffID
   162  	simulateRetries  int
   163  	retries          int
   164  }
   165  
   166  // Key returns the key used to deduplicate downloads.
   167  func (d *mockDownloadDescriptor) Key() string {
   168  	return d.id
   169  }
   170  
   171  // ID returns the ID for display purposes.
   172  func (d *mockDownloadDescriptor) ID() string {
   173  	return d.id
   174  }
   175  
   176  // DiffID should return the DiffID for this layer, or an error
   177  // if it is unknown (for example, if it has not been downloaded
   178  // before).
   179  func (d *mockDownloadDescriptor) DiffID() (layer.DiffID, error) {
   180  	if d.diffID != "" {
   181  		return d.diffID, nil
   182  	}
   183  	return "", errors.New("no diffID available")
   184  }
   185  
   186  func (d *mockDownloadDescriptor) Registered(diffID layer.DiffID) {
   187  	d.registeredDiffID = diffID
   188  }
   189  
   190  func (d *mockDownloadDescriptor) mockTarStream() io.ReadCloser {
   191  	// The mock implementation returns the ID repeated 5 times as a tar
   192  	// stream instead of actual tar data. The data is ignored except for
   193  	// computing IDs.
   194  	return io.NopCloser(bytes.NewBuffer([]byte(d.id + d.id + d.id + d.id + d.id)))
   195  }
   196  
   197  // Download is called to perform the download.
   198  func (d *mockDownloadDescriptor) Download(ctx context.Context, progressOutput progress.Output) (io.ReadCloser, int64, error) {
   199  	if d.currentDownloads != nil {
   200  		defer atomic.AddInt32(d.currentDownloads, -1)
   201  
   202  		if atomic.AddInt32(d.currentDownloads, 1) > maxDownloadConcurrency {
   203  			return nil, 0, errors.New("concurrency limit exceeded")
   204  		}
   205  	}
   206  
   207  	// Sleep a bit to simulate a time-consuming download.
   208  	for i := int64(0); i <= 10; i++ {
   209  		select {
   210  		case <-ctx.Done():
   211  			return nil, 0, ctx.Err()
   212  		case <-time.After(10 * time.Millisecond):
   213  			progressOutput.WriteProgress(progress.Progress{ID: d.ID(), Action: "Downloading", Current: i, Total: 10})
   214  		}
   215  	}
   216  
   217  	if d.retries < d.simulateRetries {
   218  		d.retries++
   219  		return nil, 0, fmt.Errorf("simulating download attempt failure %d/%d", d.retries, d.simulateRetries)
   220  	}
   221  
   222  	return d.mockTarStream(), 0, nil
   223  }
   224  
   225  func (d *mockDownloadDescriptor) Close() {
   226  }
   227  
   228  func downloadDescriptors(currentDownloads *int32) []DownloadDescriptor {
   229  	return []DownloadDescriptor{
   230  		&mockDownloadDescriptor{
   231  			currentDownloads: currentDownloads,
   232  			id:               "id1",
   233  			expectedDiffID:   layer.DiffID("sha256:68e2c75dc5c78ea9240689c60d7599766c213ae210434c53af18470ae8c53ec1"),
   234  		},
   235  		&mockDownloadDescriptor{
   236  			currentDownloads: currentDownloads,
   237  			id:               "id2",
   238  			expectedDiffID:   layer.DiffID("sha256:64a636223116aa837973a5d9c2bdd17d9b204e4f95ac423e20e65dfbb3655473"),
   239  		},
   240  		&mockDownloadDescriptor{
   241  			currentDownloads: currentDownloads,
   242  			id:               "id3",
   243  			expectedDiffID:   layer.DiffID("sha256:58745a8bbd669c25213e9de578c4da5c8ee1c836b3581432c2b50e38a6753300"),
   244  		},
   245  		&mockDownloadDescriptor{
   246  			currentDownloads: currentDownloads,
   247  			id:               "id2",
   248  			expectedDiffID:   layer.DiffID("sha256:64a636223116aa837973a5d9c2bdd17d9b204e4f95ac423e20e65dfbb3655473"),
   249  		},
   250  		&mockDownloadDescriptor{
   251  			currentDownloads: currentDownloads,
   252  			id:               "id4",
   253  			expectedDiffID:   layer.DiffID("sha256:0dfb5b9577716cc173e95af7c10289322c29a6453a1718addc00c0c5b1330936"),
   254  			simulateRetries:  1,
   255  		},
   256  		&mockDownloadDescriptor{
   257  			currentDownloads: currentDownloads,
   258  			id:               "id5",
   259  			expectedDiffID:   layer.DiffID("sha256:0a5f25fa1acbc647f6112a6276735d0fa01e4ee2aa7ec33015e337350e1ea23d"),
   260  		},
   261  	}
   262  }
   263  
   264  func TestSuccessfulDownload(t *testing.T) {
   265  	// TODO Windows: Fix this unit text
   266  	if runtime.GOOS == "windows" {
   267  		t.Skip("Needs fixing on Windows")
   268  	}
   269  
   270  	layerStore := &mockLayerStore{make(map[layer.ChainID]*mockLayer)}
   271  	ldm := NewLayerDownloadManager(layerStore, maxDownloadConcurrency, func(m *LayerDownloadManager) { m.waitDuration = time.Millisecond })
   272  
   273  	progressChan := make(chan progress.Progress)
   274  	progressDone := make(chan struct{})
   275  	receivedProgress := make(map[string]progress.Progress)
   276  
   277  	go func() {
   278  		for p := range progressChan {
   279  			receivedProgress[p.ID] = p
   280  		}
   281  		close(progressDone)
   282  	}()
   283  
   284  	var currentDownloads int32
   285  	descriptors := downloadDescriptors(&currentDownloads)
   286  
   287  	firstDescriptor := descriptors[0].(*mockDownloadDescriptor)
   288  
   289  	// Pre-register the first layer to simulate an already-existing layer
   290  	l, err := layerStore.Register(firstDescriptor.mockTarStream(), "")
   291  	if err != nil {
   292  		t.Fatal(err)
   293  	}
   294  	firstDescriptor.diffID = l.DiffID()
   295  
   296  	rootFS, releaseFunc, err := ldm.Download(context.Background(), *image.NewRootFS(), descriptors, progress.ChanOutput(progressChan))
   297  	if err != nil {
   298  		t.Fatalf("download error: %v", err)
   299  	}
   300  
   301  	releaseFunc()
   302  
   303  	close(progressChan)
   304  	<-progressDone
   305  
   306  	if len(rootFS.DiffIDs) != len(descriptors) {
   307  		t.Fatal("got wrong number of diffIDs in rootfs")
   308  	}
   309  
   310  	for i, d := range descriptors {
   311  		descriptor := d.(*mockDownloadDescriptor)
   312  
   313  		if descriptor.diffID != "" {
   314  			if receivedProgress[d.ID()].Action != "Already exists" {
   315  				t.Fatalf("did not get 'Already exists' message for %v", d.ID())
   316  			}
   317  		} else if receivedProgress[d.ID()].Action != "Pull complete" {
   318  			t.Fatalf("did not get 'Pull complete' message for %v", d.ID())
   319  		}
   320  
   321  		if rootFS.DiffIDs[i] != descriptor.expectedDiffID {
   322  			t.Fatalf("rootFS item %d has the wrong diffID (expected: %v got: %v)", i, descriptor.expectedDiffID, rootFS.DiffIDs[i])
   323  		}
   324  
   325  		if descriptor.diffID == "" && descriptor.registeredDiffID != rootFS.DiffIDs[i] {
   326  			t.Fatal("diffID mismatch between rootFS and Registered callback")
   327  		}
   328  	}
   329  }
   330  
   331  func TestCancelledDownload(t *testing.T) {
   332  	layerStore := &mockLayerStore{make(map[layer.ChainID]*mockLayer)}
   333  	ldm := NewLayerDownloadManager(layerStore, maxDownloadConcurrency, func(m *LayerDownloadManager) { m.waitDuration = time.Millisecond })
   334  	progressChan := make(chan progress.Progress)
   335  	progressDone := make(chan struct{})
   336  
   337  	go func() {
   338  		for range progressChan {
   339  		}
   340  		close(progressDone)
   341  	}()
   342  
   343  	ctx, cancel := context.WithCancel(context.Background())
   344  
   345  	go func() {
   346  		<-time.After(time.Millisecond)
   347  		cancel()
   348  	}()
   349  
   350  	descriptors := downloadDescriptors(nil)
   351  	_, _, err := ldm.Download(ctx, *image.NewRootFS(), descriptors, progress.ChanOutput(progressChan))
   352  	if err != context.Canceled {
   353  		close(progressChan)
   354  		t.Fatal("expected download to be cancelled")
   355  	}
   356  
   357  	close(progressChan)
   358  	<-progressDone
   359  }
   360  
   361  func TestMaxDownloadAttempts(t *testing.T) {
   362  	tests := []struct {
   363  		name                string
   364  		simulateRetries     int
   365  		maxDownloadAttempts int
   366  		expectedErr         string
   367  	}{
   368  		{
   369  			name:                "max-attempts=5, succeed at 2nd attempt",
   370  			simulateRetries:     1,
   371  			maxDownloadAttempts: 5,
   372  		},
   373  		{
   374  			name:                "max-attempts=5, succeed at 5th attempt",
   375  			simulateRetries:     4,
   376  			maxDownloadAttempts: 5,
   377  		},
   378  		{
   379  			name:                "max-attempts=5, fail at 5th attempt",
   380  			simulateRetries:     5,
   381  			maxDownloadAttempts: 5,
   382  			expectedErr:         "simulating download attempt failure 5/5",
   383  		},
   384  		{
   385  			name:                "max-attempts=1, fail after 1 attempt",
   386  			simulateRetries:     1,
   387  			maxDownloadAttempts: 1,
   388  			expectedErr:         "simulating download attempt failure 1/1",
   389  		},
   390  	}
   391  	for _, tc := range tests {
   392  		tc := tc
   393  		t.Run(tc.name, func(t *testing.T) {
   394  			t.Parallel()
   395  			layerStore := &mockLayerStore{make(map[layer.ChainID]*mockLayer)}
   396  			ldm := NewLayerDownloadManager(
   397  				layerStore,
   398  				maxDownloadConcurrency,
   399  				func(m *LayerDownloadManager) {
   400  					m.waitDuration = time.Millisecond
   401  					m.maxDownloadAttempts = tc.maxDownloadAttempts
   402  				})
   403  
   404  			progressChan := make(chan progress.Progress)
   405  			progressDone := make(chan struct{})
   406  
   407  			go func() {
   408  				for range progressChan {
   409  				}
   410  				close(progressDone)
   411  			}()
   412  
   413  			var currentDownloads int32
   414  			descriptors := downloadDescriptors(&currentDownloads)
   415  			descriptors[4].(*mockDownloadDescriptor).simulateRetries = tc.simulateRetries
   416  
   417  			_, _, err := ldm.Download(context.Background(), *image.NewRootFS(), descriptors, progress.ChanOutput(progressChan))
   418  			if tc.expectedErr == "" {
   419  				assert.NilError(t, err)
   420  			} else {
   421  				assert.Error(t, err, tc.expectedErr)
   422  			}
   423  		})
   424  	}
   425  }