Debian Codegraph @

fs/remote/blob_test.go

raw
1 /*
2 Copyright The containerd Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 /*
18 Copyright 2019 The Go Authors. All rights reserved.
19 Use of this source code is governed by a BSD-style
20 license that can be found in the NOTICE.md file.
21 */
22
23 package remote
24
25 import (
26 "bytes"
27 "fmt"
28 "io"
29 "mime"
30 "mime/multipart"
31 "net/http"
32 "net/textproto"
33 "sort"
34 "strconv"
35 "strings"
36 "sync"
37 "sync/atomic"
38 "testing"
39 "time"
40
41 "github.com/containerd/stargz-snapshotter/cache"
42 )
43
44 const (
45 testURL = "http://testdummy.com/v2/library/test/blobs/sha256:deadbeaf"
46 rangeHeaderPrefix = "bytes="
47 sampleChunkSize = 3
48 sampleMiddleOffset = sampleChunkSize / 2
49 sampleData1 = "0123456789"
50 lastChunkOffset1 = sampleChunkSize * (int64(len(sampleData1)) / sampleChunkSize)
51 defaultPrefetchChunkSize = 0
52 )
53
54 // Tests ReadAt and Cache method of each file.
55 func TestReadAt(t *testing.T) {
56 sizeCond := map[string]int64{
57 "single_chunk": sampleChunkSize - sampleMiddleOffset,
58 "multi_chunks": 2*sampleChunkSize + sampleMiddleOffset,
59 }
60 innerOffsetCond := map[string]int64{
61 "at_top": 0,
62 "at_middle": sampleMiddleOffset,
63 }
64 baseOffsetCond := map[string]int64{
65 "of_1st_chunk": sampleChunkSize * 0,
66 "of_2nd_chunk": sampleChunkSize * 1,
67 "of_last_chunk": sampleChunkSize * (int64(len(sampleData1)) / sampleChunkSize),
68 }
69 blobSizeCond := map[string]int64{
70 "in_1_chunk_blob": sampleChunkSize * 1,
71 "in_3_chunks_blob": sampleChunkSize * 3,
72 "in_max_size_blob": int64(len(sampleData1)),
73 }
74 prefetchChunkSizeCond := map[string]int64{
75 "single_get_prefetch": 0,
76 "multiple_get_prefetch": sampleChunkSize * 2,
77 }
78 type cacheCond struct {
79 reg region
80 mustHit bool
81 }
82 transportCond := map[string]struct {
83 allowMultiRange bool
84 cacheCond []cacheCond
85 }{
86 "with_multi_reg_with_clean_cache": {
87 allowMultiRange: true,
88 cacheCond: nil,
89 },
90 "with_single_reg_with_clean_cache": {
91 allowMultiRange: false,
92 cacheCond: nil,
93 },
94 "with_multi_reg_with_edge_filled_cache": {
95 allowMultiRange: true,
96 cacheCond: []cacheCond{
97 {region{0, sampleChunkSize - 1}, true},
98 {region{lastChunkOffset1, int64(len(sampleData1)) - 1}, true},
99 },
100 },
101 "with_single_reg_with_edge_filled_cache": {
102 allowMultiRange: false,
103 cacheCond: []cacheCond{
104 {region{0, sampleChunkSize - 1}, true},
105 {region{lastChunkOffset1, int64(len(sampleData1)) - 1}, true},
106 },
107 },
108 "with_multi_reg_with_sparse_cache": {
109 allowMultiRange: true,
110 cacheCond: []cacheCond{
111 {region{0, sampleChunkSize - 1}, true},
112 {region{2 * sampleChunkSize, 3*sampleChunkSize - 1}, true},
113 },
114 },
115 "with_single_reg_with_sparse_cache": {
116 allowMultiRange: false,
117 cacheCond: []cacheCond{
118 {region{0, sampleChunkSize - 1}, true},
119 {region{2 * sampleChunkSize, 3*sampleChunkSize - 1}, false},
120 },
121 },
122 }
123
124 for sn, size := range sizeCond {
125 for in, innero := range innerOffsetCond {
126 for bo, baseo := range baseOffsetCond {
127 for bs, blobsize := range blobSizeCond {
128 for pc, prefetchchunksize := range prefetchChunkSizeCond {
129 for tc, trCond := range transportCond {
130 t.Run(fmt.Sprintf("reading_%s_%s_%s_%s_%s_%s", sn, in, bo, bs, pc, tc), func(t *testing.T) {
131 if blobsize > int64(len(sampleData1)) {
132 t.Fatal("sample file size is larger than sample data")
133 }
134
135 wantN := size
136 offset := baseo + innero
137 if remain := blobsize - offset; remain < wantN {
138 if wantN = remain; wantN < 0 {
139 wantN = 0
140 }
141 }
142
143 // use constant string value as a data source.
144 want := strings.NewReader(sampleData1)
145
146 // data we want to get.
147 wantData := make([]byte, wantN)
148 _, err := want.ReadAt(wantData, offset)
149 if err != nil && err != io.EOF {
150 t.Fatalf("want.ReadAt (offset=%d,size=%d): %v", offset, wantN, err)
151 }
152
153 // data we get through a remote blob.
154 blob := []byte(sampleData1)[:blobsize]
155
156 // Check with allowing multi range requests
157 var cacheChunks []region
158 var except []region
159 for _, cond := range trCond.cacheCond {
160 cacheChunks = append(cacheChunks, cond.reg)
161 if cond.mustHit {
162 except = append(except, cond.reg)
163 }
164 }
165 tr := multiRoundTripper(t, blob, allowMultiRange(trCond.allowMultiRange), exceptChunks(except))
166
167 // Check ReadAt method
168 bb1 := makeTestBlob(t, blobsize, sampleChunkSize, prefetchchunksize, tr)
169 cacheAll(t, bb1, cacheChunks)
170 checkRead(t, wantData, bb1, offset, size)
171
172 // Check Cache method
173 bb2 := makeTestBlob(t, blobsize, sampleChunkSize, prefetchchunksize, tr)
174 cacheAll(t, bb2, cacheChunks)
175 checkCache(t, bb2, offset, size)
176 })
177 }
178
179 }
180 }
181 }
182 }
183 }
184 }
185
186 func cacheAll(t *testing.T, b *blob, chunks []region) {
187 for _, reg := range chunks {
188 id := b.fetcher.genID(reg)
189 w, err := b.cache.Add(id)
190 if err != nil {
191 w.Close()
192 t.Fatalf("failed to add cache %v: %v", id, err)
193 }
194 if _, err := w.Write([]byte(sampleData1[reg.b : reg.e+1])); err != nil {
195 w.Close()
196 t.Fatalf("failed to write cache %v: %v", id, err)
197 }
198 if err := w.Commit(); err != nil {
199 w.Close()
200 t.Fatalf("failed to commit cache %v: %v", id, err)
201 }
202 w.Close()
203 }
204 }
205
206 func checkRead(t *testing.T, wantData []byte, r *blob, offset int64, wantSize int64) {
207 respData := make([]byte, wantSize)
208 t.Logf("reading offset:%d, size:%d", offset, wantSize)
209 n, err := r.ReadAt(respData, offset)
210 if err != nil {
211 t.Errorf("failed to read off=%d, size=%d, blobsize=%d: %v", offset, wantSize, r.Size(), err)
212 return
213 }
214 respData = respData[:n]
215
216 if !bytes.Equal(wantData, respData) {
217 t.Errorf("off=%d, blobsize=%d; read data{size=%d,data=%q}; want (size=%d,data=%q)",
218 offset, r.Size(), len(respData), string(respData), len(wantData), string(wantData))
219 return
220 }
221
222 // check cache has valid contents.
223 checkAllCached(t, r, offset, wantSize)
224 }
225
226 func checkCache(t *testing.T, r *blob, offset int64, size int64) {
227 if err := r.Cache(offset, size); err != nil {
228 t.Errorf("failed to cache off=%d, size=%d, blobsize=%d: %v", offset, size, r.Size(), err)
229 return
230 }
231
232 // check cache has valid contents.
233 checkAllCached(t, r, offset, size)
234 }
235
236 func checkAllCached(t *testing.T, r *blob, offset, size int64) {
237 cn := 0
238 whole := region{floor(offset, r.chunkSize), ceil(offset+size-1, r.chunkSize) - 1}
239 if err := r.walkChunks(whole, func(reg region) error {
240 data := make([]byte, reg.size())
241 id := r.fetcher.genID(reg)
242
243 r, err := r.cache.Get(id)
244 if err != nil {
245 return fmt.Errorf("missed cache of region={%d,%d}(size=%d): %v", reg.b, reg.e, reg.size(), err)
246 }
247 defer r.Close()
248 if n, err := r.ReadAt(data, 0); (err != nil && err != io.EOF) || int64(n) != reg.size() {
249 return fmt.Errorf("failed to read cache of region={%d,%d}(size=%d): %v", reg.b, reg.e, reg.size(), err)
250 }
251 cn++
252 return nil
253 }); err != nil {
254 t.Errorf("%v", err)
255 return
256 }
257 }
258
259 // Tests ReadAt method for failure cases.
260 func TestFailReadAt(t *testing.T) {
261
262 // test failed http respose.
263 r := makeTestBlob(t, int64(len(sampleData1)), sampleChunkSize, defaultPrefetchChunkSize, failRoundTripper())
264 respData := make([]byte, len(sampleData1))
265 _, err := r.ReadAt(respData, 0)
266 if err == nil || err == io.EOF {
267 t.Errorf("must be fail for http failure but err=%v", err)
268 return
269 }
270
271 // test broken body with allowing multi range
272 checkBrokenBody(t, true) // with allowing multi range
273 checkBrokenBody(t, false) // with prohibiting multi range
274
275 // test broken header
276 checkBrokenHeader(t, true) // with allowing multi range
277 checkBrokenHeader(t, false) // with prohibiting multi range
278 }
279
280 func checkBrokenBody(t *testing.T, allowMultiRange bool) {
281 respData := make([]byte, len(sampleData1))
282 r := makeTestBlob(t, int64(len(sampleData1)), sampleChunkSize, defaultPrefetchChunkSize, brokenBodyRoundTripper(t, []byte(sampleData1), allowMultiRange))
283 if _, err := r.ReadAt(respData, 0); err == nil || err == io.EOF {
284 t.Errorf("must be fail for broken full body but err=%v (allowMultiRange=%v)", err, allowMultiRange)
285 return
286 }
287 r = makeTestBlob(t, int64(len(sampleData1)), sampleChunkSize, defaultPrefetchChunkSize, brokenBodyRoundTripper(t, []byte(sampleData1), allowMultiRange))
288 if _, err := r.ReadAt(respData[0:len(sampleData1)/2], 0); err == nil || err == io.EOF {
289 t.Errorf("must be fail for broken multipart body but err=%v (allowMultiRange=%v)", err, allowMultiRange)
290 return
291 }
292 }
293
294 func checkBrokenHeader(t *testing.T, allowMultiRange bool) {
295 r := makeTestBlob(t, int64(len(sampleData1)), sampleChunkSize, defaultPrefetchChunkSize, brokenHeaderRoundTripper(t, []byte(sampleData1), allowMultiRange))
296 respData := make([]byte, len(sampleData1))
297 if _, err := r.ReadAt(respData[0:len(sampleData1)/2], 0); err == nil || err == io.EOF {
298 t.Errorf("must be fail for broken multipart header but err=%v (allowMultiRange=%v)", err, allowMultiRange)
299 return
300 }
301 }
302
303 func TestParallelDownloadingBehavior(t *testing.T) {
304 type regionsBoundaries struct {
305 regions []region
306 start int64
307 end int64
308 }
309
310 type testData struct {
311 name string
312 regions [3]regionsBoundaries
313 roundtripCount int64
314 chunkSize int64
315 content string
316 }
317
318 tests := []testData{
319 {
320 name: "no_data",
321 regions: [3]regionsBoundaries{},
322 roundtripCount: 0,
323 chunkSize: 4,
324 },
325 {
326 name: "same_regions",
327 regions: [3]regionsBoundaries{
328 {
329 regions: []region{
330 {
331 b: 0,
332 e: 3,
333 },
334 },
335 start: 0,
336 end: 3,
337 },
338 {
339 regions: []region{
340 {
341 b: 0,
342 e: 3,
343 },
344 },
345 start: 0,
346 end: 3,
347 },
348 {
349 regions: []region{
350 {
351 b: 0,
352 e: 3,
353 },
354 },
355 start: 0,
356 end: 3,
357 },
358 },
359 roundtripCount: 1,
360 chunkSize: 4,
361 content: "test",
362 },
363 {
364 name: "same_regions_multiple_values",
365 regions: [3]regionsBoundaries{
366 {
367 regions: []region{
368 {
369 b: 0,
370 e: 3,
371 },
372 {
373 b: 4,
374 e: 7,
375 },
376 },
377 start: 0,
378 end: 7,
379 },
380 {
381 regions: []region{
382 {
383 b: 0,
384 e: 3,
385 },
386 {
387 b: 4,
388 e: 7,
389 },
390 },
391 start: 0,
392 end: 7,
393 },
394 {
395 regions: []region{
396 {
397 b: 0,
398 e: 3,
399 },
400 {
401 b: 4,
402 e: 7,
403 },
404 },
405 start: 0,
406 end: 7,
407 },
408 },
409 roundtripCount: 1,
410 chunkSize: 4,
411 content: "test1234",
412 },
413 {
414 name: "different_regions",
415 regions: [3]regionsBoundaries{
416 {
417 regions: []region{
418 {
419 b: 0,
420 e: 3,
421 },
422 },
423 start: 0,
424 end: 3,
425 },
426 {
427 regions: []region{
428 {
429 b: 4,
430 e: 7,
431 },
432 },
433 start: 4,
434 end: 7,
435 },
436 {
437 regions: []region{
438 {
439 b: 8,
440 e: 11,
441 },
442 },
443 start: 8,
444 end: 11,
445 },
446 },
447 roundtripCount: 3,
448 chunkSize: 4,
449 content: "test12345678",
450 },
451 {
452 name: "some_overlap",
453 regions: [3]regionsBoundaries{
454 {
455 regions: []region{
456 {
457 b: 0,
458 e: 3,
459 },
460 },
461 start: 0,
462 end: 3,
463 },
464 {
465 regions: []region{
466 {
467 b: 0,
468 e: 3,
469 },
470 },
471 start: 0,
472 end: 3,
473 },
474 {
475 regions: []region{
476 {
477 b: 4,
478 e: 7,
479 },
480 },
481 start: 4,
482 end: 7,
483 },
484 },
485 roundtripCount: 2,
486 chunkSize: 4,
487 content: "test1234",
488 },
489 }
490
491 var wg sync.WaitGroup
492 // we always run 3 routines
493 routines := 3
494
495 for _, tst := range tests {
496 var (
497 tr = &callsCountRoundTripper{
498 content: tst.content,
499 }
500 b = &blob{
501 fetcher: &httpFetcher{
502 url: "test",
503 tr: tr,
504 },
505 chunkSize: tst.chunkSize,
506 size: int64(len(tst.content)),
507 cache: cache.NewMemoryCache(),
508 }
509 )
510
511 start := make(chan struct{})
512 wg.Add(routines)
513 var contentBytes [3][]byte
514
515 for i := 0; i < routines; i++ {
516 p := make([]byte, len(tst.content))
517 contentBytes[i] = p
518 allData := make(map[region]io.Writer)
519 if i < len(tst.regions) {
520 offset := int64(0)
521 for j := range tst.regions[i].regions {
522 r := tst.regions[i].regions[j]
523 var (
524 base = positive(r.b - offset)
525 lowerUnread = positive(offset - r.b)
526 upperUnread = positive(r.e + 1 - (offset + int64(len(p))))
527 expectedSize = r.size() - upperUnread - lowerUnread
528 )
529 allData[tst.regions[i].regions[j]] = newBytesWriter(p[base:base+expectedSize], lowerUnread)
530 }
531 }
532
533 go func() {
534 <-start // by blocking on channel start we can ensure that the goroutines will run at approximately the same time
535 defer wg.Done()
536 b.fetchRange(allData, &options{})
537 }()
538 }
539 close(start) // starting
540 wg.Wait()
541
542 // We expect the number of round trip calls to be 1, since we are making 5 calls to fetchRange with
543 // overlapping intervals.
544 if tr.count != tst.roundtripCount {
545 t.Errorf("%v test failed: the round trip count should be %v, but was %v", tst.name, tst.roundtripCount, tr.count)
546 }
547 // Check for contents
548 for j := range contentBytes {
549 start := tst.regions[j].start
550 end := tst.regions[j].end
551 for i := start; i < end; i++ {
552 if contentBytes[j][i] != []byte(tst.content)[i] {
553 t.Errorf("%v test failed: the output sequence is wrong, wanted %v, got %v", tst.name, []byte(tst.content)[start:end], contentBytes[j][start:end])
554 break
555 }
556 }
557 }
558 }
559 }
560
561 func makeTestBlob(t *testing.T, size int64, chunkSize int64, prefetchChunkSize int64, fn RoundTripFunc) *blob {
562 var (
563 lastCheck time.Time
564 checkInterval time.Duration
565 )
566
567 return makeBlob(
568 &httpFetcher{
569 url: testURL,
570 tr: fn,
571 },
572 size,
573 chunkSize,
574 prefetchChunkSize,
575 cache.NewMemoryCache(),
576 lastCheck,
577 checkInterval,
578 &Resolver{},
579 time.Duration(defaultFetchTimeoutSec)*time.Second)
580 }
581
582 func TestCheckInterval(t *testing.T) {
583 var (
584 tr = &calledRoundTripper{}
585 firstTime = time.Now()
586 b = &blob{
587 fetcher: &httpFetcher{
588 url: "test",
589 tr: tr,
590 },
591 lastCheck: firstTime,
592 }
593 )
594
595 check := func(name string, checkInterval time.Duration) (time.Time, bool) {
596 beforeUpdate := time.Now()
597
598 time.Sleep(time.Millisecond)
599
600 tr.called = false
601 b.checkInterval = checkInterval
602 if err := b.Check(); err != nil {
603 t.Fatalf("%q: check mustn't be failed", name)
604 }
605
606 time.Sleep(time.Millisecond)
607
608 afterUpdate := time.Now()
609 if !tr.called {
610 return b.lastCheck, false
611 }
612 if !(b.lastCheck.After(beforeUpdate) && b.lastCheck.Before(afterUpdate)) {
613 t.Errorf("%q: updated time must be after %q and before %q but %q", name, beforeUpdate, afterUpdate, b.lastCheck)
614 }
615
616 return b.lastCheck, true
617 }
618
619 // second time(not expired yet)
620 secondTime, called := check("second time", time.Hour)
621 if called {
622 t.Error("mustn't be checked if not expired")
623 }
624 if !secondTime.Equal(firstTime) {
625 t.Errorf("lastCheck time must be same as first time(%q) but %q", firstTime, secondTime)
626 }
627
628 // third time(expired, must be checked)
629 if _, called := check("third time", 0); !called {
630 t.Error("must be called for the third time")
631 }
632 }
633
634 type callsCountRoundTripper struct {
635 count int64
636 content string
637 }
638
639 func (c *callsCountRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {
640 atomic.AddInt64(&c.count, 1)
641 time.Sleep(50 * time.Millisecond) // sleep for 50 milliseconds to emulate the http call and to make sure that we can run tests on parallel goroutines
642 convertBody := func(r io.ReadCloser) io.ReadCloser { return r }
643 header := make(http.Header)
644 header.Add("Content-Length", fmt.Sprintf("%d", len(c.content)))
645 return &http.Response{
646 StatusCode: http.StatusOK,
647 Header: header,
648 Body: convertBody(io.NopCloser(bytes.NewReader([]byte(c.content)))),
649 }, nil
650 }
651
652 type calledRoundTripper struct {
653 called bool
654 }
655
656 func (c *calledRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {
657 c.called = true
658 res = &http.Response{
659 StatusCode: http.StatusOK,
660 Header: make(http.Header),
661 Body: io.NopCloser(bytes.NewReader([]byte("test"))),
662 }
663 return
664 }
665
666 type RoundTripFunc func(req *http.Request) *http.Response
667
668 func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
669 return f(req), nil
670 }
671
672 type bodyConverter func(r io.ReadCloser) io.ReadCloser
673 type exceptChunks []region
674 type allowMultiRange bool
675
676 func multiRoundTripper(t *testing.T, contents []byte, opts ...interface{}) RoundTripFunc {
677 multiRangeEnable := true
678 doNotFetch := []region{}
679 convertBody := func(r io.ReadCloser) io.ReadCloser { return r }
680 for _, opt := range opts {
681 if v, ok := opt.(allowMultiRange); ok {
682 multiRangeEnable = bool(v)
683 } else if v, ok := opt.(exceptChunks); ok {
684 doNotFetch = []region(v)
685 } else if v, ok := opt.(bodyConverter); ok {
686 convertBody = (func(r io.ReadCloser) io.ReadCloser)(v)
687 }
688 }
689 emptyResponse := func(statusCode int) *http.Response {
690 return &http.Response{
691 StatusCode: statusCode,
692 Header: make(http.Header),
693 Body: io.NopCloser(bytes.NewReader([]byte{})),
694 }
695 }
696
697 return func(req *http.Request) *http.Response {
698 // Validate request
699 if req.Method != "GET" || req.URL.String() != testURL {
700 return emptyResponse(http.StatusBadRequest)
701 }
702 ranges := req.Header.Get("Range")
703 if ranges == "" {
704 return emptyResponse(http.StatusBadRequest)
705 }
706 if !strings.HasPrefix(ranges, rangeHeaderPrefix) {
707 return emptyResponse(http.StatusBadRequest)
708 }
709 rlist := strings.Split(ranges[len(rangeHeaderPrefix):], ",")
710 if len(rlist) == 0 {
711 return emptyResponse(http.StatusBadRequest)
712 }
713
714 // check this request can be served as one whole blob.
715 var sorted []region
716 for _, part := range rlist {
717 begin, end := parseRangeString(t, part)
718 sorted = append(sorted, region{begin, end})
719 }
720 sort.Slice(sorted, func(i, j int) bool {
721 return sorted[i].b < sorted[j].b
722 })
723 var sparse bool
724 if sorted[0].b == 0 {
725 var max int64
726 for _, reg := range sorted {
727 if reg.e > max {
728 if max < reg.b-1 {
729 sparse = true
730 break
731 }
732 max = reg.e
733 }
734 }
735 if max >= int64(len(contents)-1) && !sparse {
736 t.Logf("serving whole range %q = %d", ranges, len(contents))
737 header := make(http.Header)
738 header.Add("Content-Length", fmt.Sprintf("%d", len(contents)))
739 return &http.Response{
740 StatusCode: http.StatusOK,
741 Header: header,
742 Body: convertBody(io.NopCloser(bytes.NewReader(contents))),
743 }
744 }
745 }
746
747 if !multiRangeEnable {
748 if len(rlist) > 1 {
749 return emptyResponse(http.StatusBadRequest) // prohibiting multi range
750 }
751
752 // serve as single part response
753 begin, end := parseRangeString(t, rlist[0])
754 target := region{begin, end}
755 for _, reg := range doNotFetch {
756 if target.b <= reg.b && reg.e <= target.e {
757 t.Fatalf("Requested prohibited region of chunk(singlepart): (%d, %d) contained in fetching region (%d, %d)",
758 reg.b, reg.e, target.b, target.e)
759 }
760 }
761 header := make(http.Header)
762 header.Add("Content-Length", fmt.Sprintf("%d", target.size()))
763 header.Add("Content-Range",
764 fmt.Sprintf("bytes %d-%d/%d", target.b, target.e, len(contents)))
765 header.Add("Content-Type", "application/octet-stream")
766 part := contents[target.b : target.e+1]
767 return &http.Response{
768 StatusCode: http.StatusPartialContent,
769 Header: header,
770 Body: convertBody(io.NopCloser(bytes.NewReader(part))),
771 }
772 }
773
774 // Write multipart response.
775 var buf bytes.Buffer
776 mw := multipart.NewWriter(&buf)
777 for _, part := range rlist {
778 mh := make(textproto.MIMEHeader)
779 mh.Set("Content-Range", fmt.Sprintf("bytes %s/%d", part, len(contents)))
780 w, err := mw.CreatePart(mh)
781 if err != nil {
782 t.Fatalf("failed to create part: %v", err)
783 }
784 begin, end := parseRangeString(t, part)
785 if begin >= int64(len(contents)) {
786 // skip if out of range.
787 continue
788 }
789 if end > int64(len(contents)-1) {
790 end = int64(len(contents) - 1)
791 }
792 for _, reg := range doNotFetch {
793 if begin <= reg.b && reg.e <= end {
794 t.Fatalf("Requested prohibited region of chunk (multipart): (%d, %d) contained in fetching region (%d, %d)",
795 reg.b, reg.e, begin, end)
796 }
797 }
798 if n, err := w.Write(contents[begin : end+1]); err != nil || int64(n) != end+1-begin {
799 t.Fatalf("failed to write to part(%d-%d): %v", begin, end, err)
800 }
801 }
802 mw.Close()
803 param := map[string]string{
804 "boundary": mw.Boundary(),
805 }
806 header := make(http.Header)
807 header.Add("Content-Type", mime.FormatMediaType("multipart/text", param))
808 return &http.Response{
809 StatusCode: http.StatusPartialContent,
810 Header: header,
811 Body: convertBody(io.NopCloser(&buf)),
812 }
813 }
814 }
815
816 func failRoundTripper() RoundTripFunc {
817 return func(req *http.Request) *http.Response {
818 return &http.Response{
819 StatusCode: http.StatusInternalServerError,
820 Header: make(http.Header),
821 Body: io.NopCloser(bytes.NewReader([]byte{})),
822 }
823 }
824 }
825
826 func brokenBodyRoundTripper(t *testing.T, contents []byte, multiRange bool) RoundTripFunc {
827 breakReadCloser := func(r io.ReadCloser) io.ReadCloser {
828 defer r.Close()
829 data, err := io.ReadAll(r)
830 if err != nil {
831 t.Fatalf("failed to break read closer faild to read original: %v", err)
832 }
833 return io.NopCloser(bytes.NewReader(data[:len(data)/2]))
834 }
835 tr := multiRoundTripper(t, contents, allowMultiRange(multiRange), bodyConverter(breakReadCloser))
836 return func(req *http.Request) *http.Response {
837 return tr(req)
838 }
839 }
840
841 func brokenHeaderRoundTripper(t *testing.T, contents []byte, multiRange bool) RoundTripFunc {
842 tr := multiRoundTripper(t, contents, allowMultiRange(multiRange))
843 return func(req *http.Request) *http.Response {
844 res := tr(req)
845 res.Header = make(http.Header)
846 return res
847 }
848 }
849
850 func parseRangeString(t *testing.T, rangeString string) (int64, int64) {
851 rng := strings.Split(rangeString, "-")
852 if len(rng) != 2 {
853 t.Fatalf("falied to parse range %q", rng)
854 }
855 begin, err := strconv.ParseInt(rng[0], 10, 64)
856 if err != nil {
857 t.Fatalf("failed to parse beginning offset: %v", err)
858 }
859 end, err := strconv.ParseInt(rng[1], 10, 64)
860 if err != nil {
861 t.Fatalf("failed to parse ending offset: %v", err)
862 }
863 return begin, end
864 }